# platform/audio/desktop (vanilla-engine 0.4.0)

> https://vanillapunch.com/docs/vanilla-engine/0.4.0/api/platform/audio/desktop/

Desktop audio backend. (Windows, Mac, Linux, the engine mixer on top of cpal output)
- In place of AudioContext: opens the default output device with cpal and runs a mixer at its sample rate (mixer.rs). If there is no device it reports once and does not open again.
  There is no browser autoplay policy, so the user gesture is treated as present from the start. sample_rate(), current_time() have the same names as the web AudioContext.
- The node graph is the same as the original WebAudio and the math matches Chrome. (header comment of mixer.rs)
  One AudioPlayer = source + GainNode (+ StereoPannerNode when a nonzero pan is first set), to that bus if an output (AudioOutputNode) is given, otherwise to the output.
  One AudioBus = a GainNode connected to the output. (AudioGainNode, the original getGainNode) Players made on a bus hold a bus handle,
  so as in the original WebAudio the bus stays alive while connected players exist. The node is removed once all handles are gone.
- Context suspend (SoundSystem calls it while muted): the mixer stops rendering, so the sound and clock stop in place. (the original AudioContext.suspend) resume starts it again.
- The context clock (get_audio_context_time) is the rendered time. (the original currentTime, rises by 128 / sample rate seconds every 128-frame quantum)
- A management thread holds the stream. When the device is removed (or, except on Mac, when the default device changes), it reopens the default device with the same mixer. (the original Chrome also follows the default device)
- In place of AudioBuffer: holds decoded sound in an Arc. Cloning is cheap. decode decodes it the same way as the original Chrome decodeAudioData.
  (Opus and Vorbis in webm, ogg, mp3, wav, flac, AAC in m4a and aac. Trimming of both ends, 44100Hz, downmixed to 1 or 2 channels by the WebAudio speaker rules)
- In place of AudioStream: a sound loaded for streaming. (the original AudioLoadType.streaming, holds only the compressed source (a file path or bytes) and the trim plan)
  When played, a decoder thread per player decodes chunk by chunk into a ring buffer (128 KiB) that the mixer's streaming source reads. (streaming.rs, the samples are the same as the fully decoded buffer)
- Volume, pan and stop change right from the next render quantum. Playback rate applies from the next playback. (same as the original)
- Volume is the AudioParam of the GainNode. Setting the volume is assigning the original gain.value, and SoundSystem sets automation (setValueAtTime calls) and stop(when) as in the original.
  The current gain.value (get_gain_value) is the intrinsic value the sound thread computes every quantum.
- BeepPlayer's tones build OscillatorNode → GainNode (envelope automation) → output on the mixer like the original playTone. (the math matches Chrome, oscillator.rs)
  The waveform's band-limited tables (PeriodicWave) are built once per sample rate, as in the original context.

## AudioContext (struct)

Shared audio context. (in place of the original AudioContext, the path to the device stream and mixer)
- AudioManager holds one, and it is borrowed and read with get_audio_context. (game code does not create it directly)

Example: Open the device and read the sample rate and clock

```rust
use vanilla::AudioManager;

let audio_manager = AudioManager::new();
audio_manager.resume_context();
let audio_context = audio_manager.get_audio_context();
if let Some(audio_context) = audio_context.as_deref() {
	assert!(audio_context.sample_rate() > 0.0);
	assert!(audio_context.current_time() >= 0.0);
}
```

- `pub fn sample_rate(&self) -> f32` (method, since 0.4.0): Sample rate. (the original audioContext.sampleRate, the device's sample rate)
  - returns f32: Sample rate of the currently open output device. (Hz, the new device's when the device changes)
- `pub fn current_time(&self) -> f64` (method, since 0.4.0): Clock. (seconds, the original audioContext.currentTime)
  - returns f64: Time rendered since the context was created. (seconds, rises every 128-frame quantum and stops while suspended)

## AudioBuffer (struct) (Clone)

Decoded sound. (in place of the original AudioBuffer, cloning is just one Arc so it is cheap)
- AudioAsset holds it, and it is obtained with get_audio_buffer. Decoded on the spot even without a sound device.

Example: Decoded sound is 44100Hz, and even 5.1 channels are downmixed to 2 channels

```rust
use vanilla::{Engine, EngineConfiguration};

let engine = Engine::new(EngineConfiguration::new());
let audio_asset = engine.load_audio_asset("tests/assets/audio/flac_51.flac").unwrap();
let audio_buffer = audio_asset.get_audio_buffer().unwrap();
assert_eq!(audio_buffer.sample_rate(), 44100.0);
assert_eq!(audio_buffer.number_of_channels(), 2);
assert_eq!(audio_buffer.duration(), audio_buffer.length() as f64 / 44100.0);

let mono_asset = engine.load_audio_asset("tests/assets/audio/mp3_mono22.mp3").unwrap();
let mono_buffer = mono_asset.get_audio_buffer().unwrap();
assert_eq!(mono_buffer.number_of_channels(), 1);
assert_eq!(mono_buffer.sample_rate(), 44100.0);
```

- `pub fn duration(&self) -> f64` (method, since 0.4.0): Duration. (seconds, the original duration)
  - returns f64: Frame count / sample rate. (seconds)
- `pub fn length(&self) -> usize` (method, since 0.4.0): Frame count. (the original length)
  - returns usize: Sample count of one channel. (the length of the first channel)
- `pub fn number_of_channels(&self) -> usize` (method, since 0.4.0): Channel count. (the original numberOfChannels, on desktop 1 or 2 downmixed by the speaker rules)
  - returns usize: 1 or 2.
- `pub fn sample_rate(&self) -> f32` (method, since 0.4.0): Sample rate. (the original sampleRate, 44100)
  - returns f32: Sample rate of the decoded sound. (Hz, always 44100)

## AudioGainNode (type)

In place of the bus's GainNode. (the original AudioBus.getGainNode, shares the bus)

```rust
pub type AudioGainNode = Rc<MixerGainNode>
```

## AudioOutputNode (type)

Where the player sends its sound. (in place of the outputNode of the original AudioPlayer constructor, outputs to that bus. as_deref of AudioGainNode)

```rust
pub type AudioOutputNode<'a> = &'a MixerGainNode
```

