# resource/audioasset (vanilla.js 0.4.0)

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

Audio asset.

## AudioAsset extends Asset

Audio asset.

Example: Load a sound file and check its length

```js
import { AudioAsset } from "./build/vanilla.js";

const audioAsset = new AudioAsset();
await audioAsset.load("examples/assets/beep.wav");
const audioBuffer = audioAsset.getAudioBuffer();
console.log(audioAsset.getDuration(), audioBuffer.sampleRate, audioAsset.getLoadError());
```

- `constructor()` (constructor, since 0.0.8): Constructor.
- `setLoadType(loadType)` (method, since 0.4.0): Sets the load type. (from the next load or loadFromBytes, if already loaded it changes only after unload and loading again)
  - `loadType` string: Load type. (a value of AudioLoadType, decompressOnLoad if unknown)

  Example: Load long background music as streaming

  ```js
  import { AudioAsset, AudioLoadType } from "./build/vanilla.js";
  
  const audioAsset = new AudioAsset();
  audioAsset.setLoadType(AudioLoadType.streaming);
  await audioAsset.load("examples/assets/beep.wav");
  console.log(audioAsset.getLoadType(), audioAsset.isStreaming(), audioAsset.getDuration());
  ```

- `getLoadType()` (method, since 0.4.0): Returns the load type.
  - returns string: Load type. (a value of AudioLoadType, decompressOnLoad by default, only background music of the engine SoundSystem uses streaming when the sound table has no loadType)
- `isStreaming()` (method, since 0.4.0): Whether it was loaded as streaming. (with the automatic load type this is decided after loading)
  - returns boolean: True if loaded as streaming. (false if fully decompressed or not loaded yet)
- `getStreamUrl()` (method, since 0.4.0): URL of the streaming sound. (used as the media element's src)
  - returns string | null: A file path or blob: URL. (null if not streaming)
- `async load(assetPath)` (method, since 0.0.8): Loads the asset asynchronously.
  - `assetPath` string: Sound file path. (does nothing if already loaded)
  - returns Promise<void>: A promise resolved when fully loaded. (if fetching or decoding fails it records the reason in getLoadError and rejects, if decoding is not available it only records the reason and resolves)
- `async loadFromBytes(bytes)` (method, since 0.4.0): Loads from bytes already held. (Built-in data or a directly received file, isLoaded() is true once decoding finishes, does nothing if already loaded)
  - `bytes` ArrayBuffer | ArrayBufferView: The bytes of the sound file. (What is passed is not changed)

  Example: Load a sound from bytes already fetched

  ```js
  import { AudioAsset } from "./build/vanilla.js";
  
  const response = await fetch("examples/assets/beep.wav");
  const bytes = await response.arrayBuffer();
  const audioAsset = new AudioAsset();
  await audioAsset.loadFromBytes(bytes);
  console.log(audioAsset.isLoaded(), audioAsset.getDuration(), bytes.byteLength);
  ```

- `async decodeArrayBuffer(arrayBuffer)` (method, since 0.4.0): Decodes the sound bytes. (When done, holds the audio buffer and marks it as loaded)
  - Decoding is done with OfflineAudioContext. (It does not grab the speaker, creating it before a user gesture gives no autoplay warning,
    and receiving many assets at once does not hit the real-time AudioContext count limit) If it is unavailable, a temporary AudioContext is used.
  - `arrayBuffer` ArrayBuffer: Not used again afterward because decoding detaches it.
- `unload()` (method, since 0.4.0): Unloads the asset. (releases the audio buffer and any blob: URL this asset created, the load type stays)
- `getLoadError()` (method, since 0.4.0): The reason for the last load failure. (A string if receiving or decoding failed, otherwise null, cleared when loading starts again)
  - returns string | null: Failure reason. (null if none)
- `getAudioBuffer()` (method, since 0.0.10): Returns the audio buffer.
  - returns AudioBuffer | null: The decoded audio buffer. (null if not loaded yet or streaming)
- `getDuration()` (method, since 0.0.8): Returns the playback duration.
  - returns number: Playback duration. (seconds, 0 if not loaded yet, the metadata duration if streaming)

## Functions and constants

- `AUTOMATIC_STREAMING_BYTE_THRESHOLD` (field, since 0.4.0): File size above which automatic (AudioLoadType.automatic) picks streaming. (bytes, larger files stream)
  - Full decoding holds 44100 float32 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.

## AudioLoadType (enum)

Sound load type. (the same kind of choice as Unity AudioClip's Load Type and Unreal sound wave streaming)

Example: Stream background music, fully decompress sound effects

```js
import { AudioAsset, AudioLoadType } from "./build/vanilla.js";

const musicAsset = new AudioAsset();
musicAsset.setLoadType(AudioLoadType.streaming);
await musicAsset.load("examples/assets/beep.wav");
const effectAsset = new AudioAsset();
effectAsset.setLoadType(AudioLoadType.decompressOnLoad);
await effectAsset.load("examples/assets/beep.wav");
console.log(musicAsset.isStreaming(), musicAsset.getAudioBuffer(), effectAsset.isStreaming(), effectAsset.getDuration());
```

- `automatic` = `automatic`: Chooses by size. (files larger than AUTOMATIC_STREAMING_BYTE_THRESHOLD stream, others are fully decompressed, only for assets that choose it)
- `decompressOnLoad` = `decompressOnLoad`: Fully decompresses to PCM on load. (short sounds played often and overlapping, like sound effects, start immediately and are cheap to overlap, the default)
- `streaming` = `streaming`: Does not decompress, a media element (HTMLAudioElement) decodes and streams it bit by bit. (long sounds like background music, memory is at most the compressed file size)
