# resource/audioasset (vanilla-engine 0.4.0)

> https://vanillapunch.com/docs/vanilla-engine/0.4.0/api/resource/audioasset/

Audio asset.
- The original resource/audioasset.js. Holds the audio buffer decoded from a sound file.
- The audio buffer is filled by the backend. (AudioBuffer of platform/audio)
  Desktop: an AudioBuffer holding the decoded sound in an Arc. (platform/audio/decode decodes it to the same length, sample rate (44100) and samples as the original Chrome decodeAudioData.
  Opus and Vorbis in webm, ogg, mp3, wav, flac, AAC in m4a and aac. The format is told by content, not extension)
  Web: the same WebAudio AudioBuffer as the original. (decoded with OfflineAudioContext, or a temporary AudioContext if missing)
- Reading:
  On desktop load / load_from_bytes read and decode the file on the spot before returning. Err on failure.
  Web cannot block, so load sets up fetch and decoding and returns Ok right away. When done, is_loaded() becomes true,
  and on failure the reason stays in get_load_error(). It may be loaded into a player before that, and play does nothing while there is no buffer.
  load, load_from_bytes, load_from_asset return an AudioLoadHandle that can be awaited as in the original. Ok once decoding finishes, the reason (the original reject) on failure.
  (desktop, which knows failure on the spot, checks it right away with the handle's get_load_error) An asset whose read has already been started can also be awaited with wait_for_load().await.
  In the engine, engine.load_audio_asset("sounds/hit.ogg") reads a path relative to the asset folder.
- Load type: set_load_type(AudioLoadType). As in the original the default is full decoding (DecompressOnLoad), and only background music of the engine SoundSystem streams when the sound table has no load_type.
  Streaming does not decode up front and holds only the compressed source, decoding a little at a time while playing. On desktop a decoder thread decodes chunk by chunk into a ring buffer for the mixer
  (platform/audio/streaming.rs, the same samples as the fully decoded buffer), and on the web, as in the original, an HTMLAudioElement is connected to the player's GainNode through a MediaElementAudioSourceNode.
  Automatic streams only files larger than AUTOMATIC_STREAMING_BYTE_THRESHOLD (1 MiB).
- Differences from the original:
  There is no Asset base class (asset type). Read failures are reported with Err instead of exceptions. (the reason stays in get_load_error() like the original getLoadError)
  It is used as `Rc<AudioAsset>` so players can share it, and its inside is a RefCell so it can be filled after decoding finishes on web.

## AudioLoadHandle (struct) (Clone, std::fmt::Debug, IntoFuture)

Audio load handle. (returned by AudioAsset's load functions. Stands in for the Promise of the original load, shares the asset)

Example: Bytes that are not sound fail on the spot on desktop

```rust
use std::rc::Rc;
use vanilla::AudioAsset;

let audio_asset = Rc::new(AudioAsset::new());
let audio_load_handle = audio_asset.load_from_bytes(vec![0, 1, 2, 3]);
assert!(audio_load_handle.is_finished());
assert!(audio_load_handle.get_load_error().is_some());
assert!(!audio_load_handle.get_audio_asset().is_loaded());
```

- `pub fn get_audio_asset(&self) -> &Rc<AudioAsset>` (method, since 0.4.0): The asset being read.
  - returns &Rc<AudioAsset>: Audio asset shared by this handle.
- `pub fn get_load_error(&self) -> Option<String>` (method, since 0.4.0): Reason the read failed. (known on the spot on desktop, after decoding finishes on web)
  - returns Option<String>: Failure reason. None while reading or once read.
- `pub fn is_finished(&self) -> bool` (method, since 0.4.0): Whether it finished. (decoding finished or failed)
  - returns bool: true if decoding finished or failed.

## AudioLoadFuture (struct) (Clone, Debug, Future)

Future that waits for an audio read. (made by awaiting AudioLoadHandle or returned by wait_for_load. Does not finish for an asset whose read was never started)
- Finishes with Ok(()) once decoding finishes, Err(reason) on failure.

Example: Wait for a sound read inside an engine task

```rust
use std::path::Path;
use std::rc::Rc;
use vanilla::{AudioAsset, Engine, EngineConfiguration};

let engine = Engine::new(EngineConfiguration::new());
let audio_asset = Rc::new(AudioAsset::new());
audio_asset.load(Path::new("tests/assets/audio/wav_s16_stereo.wav"));
let audio_load_future = audio_asset.wait_for_load();
let task_handle = engine.spawn_task(|_engine_context| async move {
	assert!(audio_load_future.await.is_ok());
});
assert!(task_handle.is_finished());
```

## AudioAsset (struct) (Default)

Audio asset.
- Used as `Rc<AudioAsset>` so players can share it. That is why the load functions are called on an Rc.

Example: Read a sound by asset path and check its duration

```rust
use std::rc::Rc;
use vanilla::{AudioAsset, Engine, EngineConfiguration};

let engine = Engine::new(EngineConfiguration::new());
let audio_asset = Rc::new(AudioAsset::new());
let audio_load_handle = audio_asset.load_from_asset(&engine, "tests/assets/audio/wav_s16_stereo.wav");
assert!(audio_load_handle.get_load_error().is_none());
assert!(audio_asset.is_loaded());
assert!(audio_asset.get_duration() > 0.0);
assert!(audio_asset.get_audio_buffer().is_some());
```

- `pub fn new() -> AudioAsset` (constructor, since 0.3.2): Creates one. (an empty asset, filled with load)
  - returns AudioAsset: Audio asset with neither a buffer nor a failure reason.
- `pub fn load(self: &Rc<AudioAsset>, asset_path: &Path) -> AudioLoadHandle` (method, since 0.3.2): Reads from a file. (desktop: reads and decodes right away. Web: fetches the path as a URL and sets up decoding, returns a handle that can be awaited)
  - Does nothing if already loaded.
  - Clears the previous failure reason before reading. On failure the reason stays in get_load_error.
  - `asset_path` &Path: Sound file path. (on desktop the file path as is, on the web the URL to fetch, use load_from_asset to load relative to the asset folder)
  - returns AudioLoadHandle: Load handle. (on desktop, decoding has already finished on the spot)

  Example: Read by file path, and a missing file leaves a reason

  ```rust
  use std::path::Path;
  use std::rc::Rc;
  use vanilla::AudioAsset;
  
  let audio_asset = Rc::new(AudioAsset::new());
  audio_asset.load(Path::new("tests/assets/audio/wav_u8_mono8k.wav"));
  assert!(audio_asset.is_loaded());
  assert!((audio_asset.get_duration() - 0.25).abs() < 0.01);
  
  let missing_asset = Rc::new(AudioAsset::new());
  let audio_load_handle = missing_asset.load(Path::new("tests/assets/audio/missing.wav"));
  assert!(audio_load_handle.get_load_error().is_some());
  assert_eq!(missing_asset.get_duration(), 0.0);
  ```

- `pub fn load_from_asset(self: &Rc<AudioAsset>, engine: &Engine, relative_path: &str) -> AudioLoadHandle` (method, since 0.4.0): Reads by asset path. (desktop uses the asset folder candidates, web is relative to asset_base_url, "data:" URLs work too. In place of the original load(path), returns a handle that can be awaited)
  - On desktop, data: URLs are decoded by telling the bytes apart by content without looking at the type. (same as the original decodeAudioData, on web the browser fetch decodes it)
  - On desktop, if a data: URL cannot be decoded, the failure reason is left.
  - `engine` &Engine: Engine holding the asset folder candidates and web base URL.
  - `relative_path` &str: Path relative to the asset folder, or a "data:" URL.
  - returns AudioLoadHandle: Load handle. (on desktop, decoding has already finished on the spot)
- `pub fn load_from_bytes(self: &Rc<AudioAsset>, bytes: Vec<u8>) -> AudioLoadHandle` (method, since 0.3.2): Reads from memory. (the file content as is. Desktop: decodes right away. Web: sets up decoding, returns a handle that can be awaited)
  - Does nothing if already loaded. The format is told by content without an extension.
  - `bytes` Vec<u8>: Sound file bytes. (wav, mp3, ogg, webm, flac, m4a, aac)
  - returns AudioLoadHandle: Load handle. (on desktop, decoding has already finished on the spot)

  Example: Decode file bytes from memory

  ```rust
  use std::rc::Rc;
  use vanilla::AudioAsset;
  
  let wav_bytes = std::fs::read("tests/assets/audio/wav_s16_stereo.wav").expect("wav file");
  let audio_asset = Rc::new(AudioAsset::new());
  let audio_load_handle = audio_asset.load_from_bytes(wav_bytes);
  assert!(audio_load_handle.is_finished());
  assert!(audio_asset.is_loaded());
  ```

- `pub fn is_loaded(&self) -> bool` (method, since 0.3.2): Whether it is loaded.
  - returns bool: true if a decoded buffer is present.
- `pub fn get_load_error(&self) -> Option<String>` (method, since 0.3.2): Reason the last read failed. (known on web after decoding finishes)
  - returns Option<String>: Failure reason. None if it never failed or a read was started again.
- `pub fn wait_for_load(self: &Rc<AudioAsset>) -> AudioLoadFuture` (method, since 0.4.0): Future that waits until decoding finishes. (the await of the original await audioAsset.load(), awaited inside an engine task. The reason on failure)
  - Shares the asset instead of borrowing it. Does not finish for an asset whose read was never started.
  - returns AudioLoadFuture: Future that finishes with Ok(()) once decoding finishes, Err(reason) on failure.
- `pub fn get_load_handle(self: &Rc<AudioAsset>) -> AudioLoadHandle` (method, since 0.4.0): Load handle. (shares the asset, for gathering and waiting on ones after a read has started)
  - returns AudioLoadHandle: New load handle sharing this asset.
- `pub fn set_load_type(&self, load_type: AudioLoadType)` (method, since 0.4.0): Sets the load type. (from the next load, load_from_bytes; an asset already loaded does not change)
  - `load_type` AudioLoadType: Load type.

  Example: Loading long background music for streaming

  ```rust
  use std::path::Path;
  use std::rc::Rc;
  use vanilla::{AudioAsset, AudioLoadType};
  
  let audio_asset = Rc::new(AudioAsset::new());
  audio_asset.set_load_type(AudioLoadType::Streaming);
  audio_asset.load(Path::new("tests/assets/audio/vorbis_stereo.ogg"));
  assert_eq!(audio_asset.get_load_type(), AudioLoadType::Streaming);
  assert!(audio_asset.is_streaming());
  assert!(audio_asset.get_duration() > 0.0);
  ```

- `pub fn get_load_type(&self) -> AudioLoadType` (method, since 0.4.0): Returns the load type.
  - returns AudioLoadType: Load type. (DecompressOnLoad by default, only background music of the engine SoundSystem uses Streaming when the sound table has no load_type)
- `pub fn is_streaming(&self) -> bool` (method, since 0.4.0): Whether it was loaded for streaming. (with the Automatic load type this is decided after loading)
  - returns bool: true if loaded for streaming. (false if fully decoded or before loading)
- `pub fn get_stream_url(&self) -> Option<String>` (method, since 0.4.0): Address of the streaming sound. (the original getStreamUrl, the media element src on the web)
  - returns Option<String>: On the web the file URL or a blob: URL as in the original, on desktop the path when loaded from a file. (None for desktop streaming loaded from memory or when not streaming)
- `pub fn get_audio_buffer(&self) -> Option<AudioBuffer>` (method, since 0.3.2): Returns the audio buffer. (cheap clone: Arc on desktop, a JavaScript object reference on web)
  - returns Option<AudioBuffer>: Decoded buffer. None before it is read, if it failed, or when streaming.
- `pub fn get_duration(&self) -> f64` (method, since 0.3.2): Returns the duration. (seconds, 0 before loading)
  - returns f64: Duration of the buffer. (seconds) When streaming, the length the container reports (in place of the original media element metadata duration; on desktop it becomes the decoded length once decoded to the end). 0 before loading.

## Functions and constants

- `pub const AUTOMATIC_STREAMING_BYTE_THRESHOLD: u64 = 1024 * 1024` (field, since 0.4.0): File size above which automatic (AudioLoadType::Automatic) picks streaming. (bytes, larger files stream)
  - Full decoding holds 44100 f32 values per channel per second. (about 345 KiB per stereo second, about 61 MiB for 3 minutes)
    1 MiB of 128 kbps MP3 is about 65 seconds, about 22 MiB when decoded. Sound effects are almost always smaller, and a WAV larger than this is still only around 6 seconds, so streaming it is fine.
  - returns u64

  Example: A file under the threshold is fully decoded even with automatic

  ```rust
  use std::path::Path;
  use std::rc::Rc;
  use vanilla::{AudioAsset, AudioLoadType, AUTOMATIC_STREAMING_BYTE_THRESHOLD};
  
  let path = Path::new("tests/assets/audio/wav_s16_stereo.wav");
  assert!(std::fs::metadata(path).unwrap().len() <= AUTOMATIC_STREAMING_BYTE_THRESHOLD);
  let audio_asset = Rc::new(AudioAsset::new());
  audio_asset.set_load_type(AudioLoadType::Automatic);
  audio_asset.load(path);
  assert!(!audio_asset.is_streaming());
  assert!(audio_asset.get_audio_buffer().is_some());
  ```

## AudioLoadType (enum) (Clone, Copy, Debug, Default, PartialEq, Eq, Hash)

Sound load type. (the original AudioLoadType, the same family as Unity AudioClip Load Type and Unreal sound wave streaming)

Example: Background music streams, sound effects are fully decoded

```rust
use std::path::Path;
use std::rc::Rc;
use vanilla::{AudioAsset, AudioLoadType};

let music_asset = Rc::new(AudioAsset::new());
music_asset.set_load_type(AudioLoadType::Streaming);
music_asset.load(Path::new("tests/assets/audio/mp3_stereo.mp3"));
let effect_asset = Rc::new(AudioAsset::new());
effect_asset.set_load_type(AudioLoadType::DecompressOnLoad);
effect_asset.load(Path::new("tests/assets/audio/mp3_stereo.mp3"));
assert!(music_asset.is_streaming());
assert!(music_asset.get_audio_buffer().is_none());
assert!(!effect_asset.is_streaming());
assert!((music_asset.get_duration() - effect_asset.get_duration()).abs() < 0.001);
```

- `Automatic`: Picks by size. (files larger than AUTOMATIC_STREAMING_BYTE_THRESHOLD stream, otherwise full decoding, only for assets that choose it)
- `DecompressOnLoad`: Fully decodes to PCM on load. (short sounds played often and overlapping, like sound effects; starts immediately and overlapping is cheap, the default)
- `Streaming`: Does not decode up front and decodes a little at a time while playing. (long sounds like background music; memory is at most the compressed file size, plus a 128 KiB ring buffer per player on desktop)
