# core/soundsystem (vanilla-engine 0.4.0)

> https://vanillapunch.com/docs/vanilla-engine/0.4.0/api/core/soundsystem/

Background music and sound effects handled by a sound table. (SoundSystem of vanilla.js core/soundsystem.js)
- Uses AudioManager and AudioAsset. Does not synthesize sound, only plays files.
- Each row of the sound table is SoundRow { id, paths, volume, minimum_interval, is_music, maximum_voices, pitch_variation, play_seconds, fade_out_seconds, load_type }.
  paths: a group of multiple recordings of the same sound. Each time it plays, one of the loaded ones is picked, never the same as the one just before.
  minimum_interval: interval before the same sound can play again. (seconds, so it does not pile up and get noisy)
  maximum_voices: number of copies of the same sound that can play at once. (over that, the oldest is cut, None means up to the total sound effect count, 0 means one as in the original)
  pitch_variation: ratio by which the pitch wobbles each time it plays. (0.05 means ±5%)
  play_seconds, fade_out_seconds: plays only the first play_seconds seconds of a sound effect and fades it out over fade_out_seconds seconds. (0 means to the end)
  load_type: load type. (AudioLoadType, None means Streaming for background music and DecompressOnLoad for sound effects; sound effects overlap, so they must be fully decoded to play)
- Volume: background music = music volume × music ratio × sound volume, sound effect = effect volume × sound volume × volume at the call.
  Music and effect volumes are applied on buses (AudioBus from get_music_bus, get_effect_bus), and follow changes with a 0.05 second time constant. (the original setTargetAtTime)
  Buses are created after the first press. (None before that) Players created from a bus (AudioBus::create_audio_player) also follow the set volume and mute.
- Background music remembers what was requested (get_music_id) and plays it then if it is not loaded yet or before the first press. ("" stops it)
  It can crossfade (fade_seconds), and remembers where each sound stopped so it can resume. (is_resumed) It does not play if the first file failed to load.
- Mute takes priority over the set volume. If any of the following holds, no sound is made.
  External mute (set_external_mute_provider, platform SDK or ads), user mute (set_user_muted), the page being hidden (another tab, app switch),
  the window losing focus (blur) on touch-primary devices. On iPhone the page-hidden notification arrives after the app goes down, so audio freezes without stopping and
  the last sound fragment repeats, but the focus-lost notification comes before that. Desktop (mouse) also loses focus when clicking outside the canvas, so it does not follow this.
  It is released when focus returns, the screen is pressed, or the page becomes visible again.
- While muted, the AudioContext is suspended too. (woken when released) On iPhone, if an app switch or an interstitial ad takes over a running AudioContext, waking it on return
  makes no sound, so it suspends itself beforehand. If it still does not run after being released, it tries waking it again every 0.5 seconds.
- If allowed (set_autoplay_allowed_provider, allowed if not given), it tries waking once on the first update even before a press. If blocked, the engine wakes it on the first press.
  Before the first press (user gesture) or when the AudioContext is not running, sound effects are not played. (so sounds called while suspended do not all play at once on wake)
- Sound files are loaded in the background so they do not block play. (on the web they play once decoding finishes) Sounds that fail to load simply do not play.
- Time: the same-sound interval and the re-wake interval use the wall clock (web_time::Instant) like the original performance.now(), and volume following, fade out,
  and the music's stopped position use the AudioContext clock (AudioManager::get_context_time) as in the original.
- Shared sound: set_sound_system, read_sound_system. (the original module variable, one per thread)
- Differences from the original:
  - It takes the engine instead of AudioManager at creation. The original attaches listeners to document and window, but the Rust version receives them through the engine's page events (PageEvent).
    The AudioContext is suspended or woken right where the event arrives (the sound stops immediately), and cutting sound effects happens on the next update.
  - load_sounds, load_sound take the engine to resolve paths relative to the asset folder. (in the original the browser resolves them against the page address) Desktop reads them on the spot.
    load_sounds returns an awaitable SoundLoadHandle as in the original. (waits until all requested sounds are loaded or fail, same as wait_for_load().await)
  - Volume changes and fade out are left to the sound device as in the original, with GainNode AudioParam automation (value assignment, setValueAtTime, linearRampToValueAtTime, setTargetAtTime,
    cancelScheduledValues) and source.stop(when). On the web they are applied to WebAudio, on desktop to the mixer (same math as Chromium).
    The original { source, gainNode } is one AudioPlayer created from a bus, and finished sounds (the original onended) are removed from the list in update.
    As in the original, values set with the bus's set_volume, mute last until SoundSystem applies the volume again.
  - Picking from a group and wobbling the pitch use the engine's math::random (seeded with the time on first use) in place of the original Math.random.
  - add_sound_asset (adding a sound not loaded from a file) and get_effect_voice_count were made in the Rust version first. (also added to the original under the same names)

## SoundLoadHandle (struct) (Clone, Debug, std::future::IntoFuture)

Sound load handle. (returned by SoundSystem::load_sounds. In place of the original loadSounds's Promise, it shares the requested sound assets)
- Awaiting it directly waits until all requested sounds are loaded or fail. (sounds that fail are skipped, and it returns no value)

Example: Play background music after waiting for all loads

```rust
use std::cell::RefCell;
use std::rc::Rc;
use vanilla::{Engine, EngineConfiguration, SoundRow, SoundSystem};

let engine = Engine::new(EngineConfiguration::new());
let sound_table = vec![SoundRow::create_music("field", "tests/assets/audio/vorbis_stereo.ogg", 0.6)];
let sound_system = Rc::new(RefCell::new(SoundSystem::new(&engine, sound_table)));
let sound_load_handle = sound_system.borrow_mut().load_sounds(&engine);
let task_sound_system = sound_system.clone();
engine.spawn_task(move |_engine_context| async move {
	sound_load_handle.await;
	task_sound_system.borrow_mut().play_music("field", 0.5, false);
});
```

## SoundLoadFuture (struct) (Clone, Debug, std::future::Future)

Future that waits for sounds to load. (until all are loaded or fail, sounds that fail are skipped as in the original)
- Returned by awaiting a SoundLoadHandle or by SoundSystem::wait_for_load. Await it inside an engine task.

Example: Finishes even with failed files mixed in (desktop reads on the spot and finishes on the first poll)

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

let engine = Engine::new(EngineConfiguration::new());
let hit_row = SoundRow::create_effect("hit", &["tests/assets/audio/wav_s16_stereo.wav", "tests/assets/audio/missing.wav"], 0.8);
let mut sound_system = SoundSystem::new(&engine, vec![hit_row.clone()]);
sound_system.load_sound(&engine, &hit_row);
let sound_load_future = sound_system.wait_for_load();
let task_handle = engine.spawn_task(|_engine_context| async move {
	sound_load_future.await;
});
assert!(task_handle.is_finished());
```

## SoundRow (struct) (Clone, Debug)

One row of the sound table.
- Create with create_effect, create_music and write the other fields directly.

Example: A sound effect with a recording group and background music

```rust
use vanilla::SoundRow;

let mut hit_row = SoundRow::create_effect("hit", &["tests/assets/audio/wav_s16_stereo.wav", "tests/assets/audio/mp3_stereo.mp3"], 0.8);
hit_row.minimum_interval = 0.05;
hit_row.maximum_voices = Some(3);
hit_row.pitch_variation = 0.05;
assert_eq!(hit_row.paths.len(), 2);
assert!(!hit_row.is_music);

let field_row = SoundRow::create_music("field", "tests/assets/audio/vorbis_stereo.ogg", 0.6);
assert!(field_row.is_music);
assert_eq!(field_row.paths, vec![String::from("tests/assets/audio/vorbis_stereo.ogg")]);
assert_eq!(field_row.maximum_voices, None);
```

- `pub id: String` (field, since 0.4.0): Sound name. (the id passed to play_effect, play_music)
  - returns String
- `pub paths: Vec<String>` (field, since 0.4.0): File paths of a group of multiple recordings of the same sound. (relative to the asset folder, sound effects pick one of the loaded ones different from the one just before each time, background music plays only the first file)
  - returns Vec<String>
- `pub volume: f64` (field, since 0.4.0): Sound volume. (0 ~ 1, sound effects multiply it by the volume at the call then clamp to 0 ~ 1)
  - returns f64
- `pub minimum_interval: f64` (field, since 0.4.0): Interval before the same sound effect can play again. (seconds, 0 does not block)
  - returns f64
- `pub is_music: bool` (field, since 0.4.0): Whether it is a background music row. (load_sounds loads sound effects first and background music later)
  - returns bool
- `pub maximum_voices: Option<usize>` (field, since 0.4.0): Number of copies of the same sound effect that can play at once. (over that, the oldest is cut, None means up to the total sound effect count of 12, 0 means one)
  - returns Option<usize>
- `pub pitch_variation: f64` (field, since 0.4.0): Ratio by which the pitch wobbles each time it plays. (0.05 means ±5%, 0 means no wobble)
  - returns f64
- `pub play_seconds: f64` (field, since 0.4.0): Time to play the sound effect from the start. (seconds, 0 means to the end)
  - returns f64
- `pub fade_out_seconds: f64` (field, since 0.4.0): Time to fade out after play_seconds. (seconds, unused if play_seconds is 0)
  - returns f64
- `pub load_type: Option<AudioLoadType>` (field, since 0.4.0): Load type. (None means Streaming for background music and DecompressOnLoad for sound effects, the original sound table loadType)
  - returns Option<AudioLoadType>
- `pub fn create_effect(id: &str, paths: &[&str], volume: f64) -> SoundRow` (static, since 0.4.0): One sound effect row. (other fields default)
  - `id` &str: Sound name.
  - `paths` &[&str]: File paths recording the same sound. (relative to the asset folder)
  - `volume` f64: Sound volume. (0 ~ 1)
  - returns SoundRow: Sound effect row. (minimum_interval, pitch_variation, play_seconds, fade_out_seconds are 0, maximum_voices and load_type are None)
- `pub fn create_music(id: &str, path: &str, volume: f64) -> SoundRow` (static, since 0.4.0): One background music row.
  - `id` &str: Sound name.
  - `path` &str: Music file path. (relative to the asset folder)
  - `volume` f64: Sound volume. (0 ~ 1)
  - returns SoundRow: Background music row. (is_music is true, one path, other fields same as create_effect)

## SoundSystem (struct)

Background music and sound effects handled by a sound table. (the original SoundSystem, shares the engine's AudioManager and mutes via page events)
- Call update every frame. Buses are created in the update after the first press.

Example: Create and set volumes (the sound device opens on the first update)

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

let engine = Engine::new(EngineConfiguration::new());
let sound_table = vec![
	SoundRow::create_effect("hit", &["tests/assets/audio/wav_s16_stereo.wav"], 0.8),
	SoundRow::create_music("field", "tests/assets/audio/vorbis_stereo.ogg", 0.6),
];
let mut sound_system = SoundSystem::new(&engine, sound_table);
sound_system.set_music_volume(0.5);
sound_system.set_sound_effect_volume(2.0);
assert_eq!(sound_system.get_music_volume(), 0.5);
assert_eq!(sound_system.get_sound_effect_volume(), 1.0);
assert!(sound_system.get_music_bus().is_none());
assert_eq!(sound_system.get_music_id(), "");
```

Example: Play background music in a scene and play a sound effect on press

```rust
use vanilla::{Engine, EngineConfiguration, Scene, SceneBase, SoundRow, SoundSystem, Vector2};

struct MainScene {
	scene_base: SceneBase,
	sound_system: Option<SoundSystem>,
}

impl Scene for MainScene {
	fn get_scene_base(&self) -> &SceneBase {
		&self.scene_base
	}

	fn get_scene_base_mut(&mut self) -> &mut SceneBase {
		&mut self.scene_base
	}

	fn load(&mut self, engine: &Engine) {
		let sound_table = vec![
			SoundRow::create_effect("hit", &["tests/assets/audio/wav_s16_stereo.wav"], 0.8),
			SoundRow::create_music("field", "tests/assets/audio/vorbis_stereo.ogg", 0.6),
		];
		let mut sound_system = SoundSystem::new(engine, sound_table);
		sound_system.load_sounds(engine);
		sound_system.play_music("field", 1.0, false);
		self.sound_system = Some(sound_system);
	}

	fn tick(&mut self, time_delta: f64) {
		self.scene_base.tick(time_delta);
		if let Some(sound_system) = &mut self.sound_system {
			sound_system.update();
		}
	}

	fn touch_press(&mut self, _view_input_position: Vector2) {
		if let Some(sound_system) = &mut self.sound_system {
			sound_system.play_effect("hit", 1.0, 0.0);
		}
	}
}

let engine = Engine::new(EngineConfiguration::new());
let main_scene = MainScene {
	scene_base: SceneBase::new(),
	sound_system: None,
};
engine.run(Box::new(main_scene)).unwrap();
```

- `pub fn new(engine: &Engine, sound_table: Vec<SoundRow>) -> SoundSystem` (constructor, since 0.4.0): Creates. (takes the sound table, loading is done by load_sounds, whether to mute when the window loses focus is decided by the current primary input)
  - Shares the engine's AudioManager and attaches a page event listener.
  - `engine` &Engine: Engine that shares the AudioManager and sends page events. (whether the page is hidden is also read from here)
  - `sound_table` Vec<SoundRow>: Sound table. (for the same id, the later row wins)
  - returns SoundSystem: A new sound system. (nothing loaded and no buses, all volumes 1)

  Example: Create with an empty table and add rows later

  ```rust
  use vanilla::{Engine, EngineConfiguration, SoundRow, SoundSystem};
  
  let engine = Engine::new(EngineConfiguration::new());
  let mut sound_system = SoundSystem::new(&engine, Vec::new());
  sound_system.add_sounds(vec![SoundRow::create_effect("coin", &["tests/assets/audio/wav_s16_stereo.wav"], 1.0)]);
  assert_eq!(sound_system.get_effect_voice_count(), 0);
  assert!(!sound_system.is_user_muted());
  ```

- `pub fn add_sounds(&mut self, sound_table: Vec<SoundRow>)` (method, since 0.4.0): Adds rows to the sound table. (replaces the same id, loading is done by load_sounds)
  - `sound_table` Vec<SoundRow>: Rows to add. (replaces a row with the same id)
- `pub fn set_external_mute_provider(&mut self, external_mute_provider: Option<Rc<dyn Fn() -> bool>>)` (method, since 0.4.0): Sets the function that reads the external mute. (platform SDK mute, while showing a rewarded ad, etc., read every frame and on page events, None for none)
  - `external_mute_provider` Option<Rc<dyn Fn() -> bool>>: Function that returns true if it should be muted. (None ignores the external mute)

  Example: Mute while showing an ad

  ```rust
  use std::cell::Cell;
  use std::rc::Rc;
  use vanilla::{Engine, EngineConfiguration, SoundSystem};
  
  let engine = Engine::new(EngineConfiguration::new());
  let mut sound_system = SoundSystem::new(&engine, Vec::new());
  let is_advertisement_showing = Rc::new(Cell::new(false));
  let is_advertisement_showing_for_provider = is_advertisement_showing.clone();
  sound_system.set_external_mute_provider(Some(Rc::new(move || is_advertisement_showing_for_provider.get())));
  assert!(!sound_system.read_muted());
  is_advertisement_showing.set(true);
  assert!(sound_system.read_muted());
  ```

- `pub fn get_external_mute_provider(&self) -> Option<Rc<dyn Fn() -> bool>>` (method, since 0.4.0): Returns the function that reads external mute.
  - returns Option<Rc<dyn Fn() -> bool>>: The set function. (None if none)
- `pub fn set_autoplay_allowed_provider(&mut self, autoplay_allowed_provider: Option<Rc<dyn Fn() -> bool>>)` (method, since 0.4.0): Sets the function that reads whether waking may be tried before a press. (a function returning false on platforms where the webview blocks it, None means allowed, read once on the first update)
  - `autoplay_allowed_provider` Option<Rc<dyn Fn() -> bool>>: Function that returns true if waking may be tried. (None means allowed)

  Example: Do not wake before a press (set before the first update)

  ```rust
  use std::rc::Rc;
  use vanilla::{Engine, EngineConfiguration, SoundSystem};
  
  let engine = Engine::new(EngineConfiguration::new());
  let mut sound_system = SoundSystem::new(&engine, Vec::new());
  sound_system.set_autoplay_allowed_provider(Some(Rc::new(|| false)));
  let autoplay_allowed_provider = sound_system.get_autoplay_allowed_provider().unwrap();
  assert!(!autoplay_allowed_provider());
  ```

- `pub fn get_autoplay_allowed_provider(&self) -> Option<Rc<dyn Fn() -> bool>>` (method, since 0.4.0): Returns the function that reads whether waking before a press is allowed.
  - returns Option<Rc<dyn Fn() -> bool>>: The set function. (None if none, treated as allowed)
- `pub fn get_audio_manager(&self) -> &AudioManager` (method, since 0.4.0): The engine's AudioManager. (a shared handle)
  - returns &AudioManager: AudioManager that sees the same AudioContext as the engine.
- `pub fn get_music_bus(&self) -> Option<&AudioBus>` (method, since 0.4.0): Background music and sound effect buses. (the original getMusicBus, getEffectBus, None before the first press)
  - returns Option<&AudioBus>: Background music bus. (None before the update after the first press or if the AudioContext could not be created)
- `pub fn get_effect_bus(&self) -> Option<&AudioBus>` (method, since 0.4.0): Sound effect bus. (the original getEffectBus, None before the first press)
  - returns Option<&AudioBus>: Sound effect bus. (None before the update after the first press or if the AudioContext could not be created)
- `pub fn get_music_id(&self) -> &str` (method, since 0.4.0): Background music requested to play. ("" if none)
  - returns &str: Requested background music id. ("" if none)
- `pub fn get_music_volume(&self) -> f64` (method, since 0.4.0): Music volume setting.
  - returns f64: Music volume setting. (0 ~ 1, initially 1)
- `pub fn get_music_scale(&self) -> f64` (method, since 0.4.0): Music ratio. (half volume for the pause window, etc.)
  - returns f64: Music ratio. (0 ~ 1, initially 1)
- `pub fn get_sound_effect_volume(&self) -> f64` (method, since 0.4.0): Sound effect volume setting.
  - returns f64: Sound effect volume setting. (0 ~ 1, initially 1)
- `pub fn is_user_muted(&self) -> bool` (method, since 0.4.0): Whether the user's mute button is pressed.
  - returns bool: True if user mute is set.
- `pub fn is_page_hidden(&self) -> bool` (method, since 0.4.0): Whether the page is hidden.
  - returns bool: True if the page is hidden. (starts from the engine's state at creation and changes with page events)
- `pub fn is_blur_mute_enabled(&self) -> bool` (method, since 0.4.0): Whether to mute when the window loses focus. (touch-primary devices)
  - returns bool: True if it is a touch-primary device that mutes on losing focus. (decided at creation)
- `pub fn is_window_blurred(&self) -> bool` (method, since 0.4.0): Whether the window has lost focus. (true only on devices that mute)
  - returns bool: True if muted from losing focus.
- `pub fn is_context_paused(&self) -> bool` (method, since 0.4.0): Whether the AudioContext has been stopped due to mute.
  - returns bool: True if the AudioContext was suspended by mute.
- `pub fn get_last_context_resume_time(&self) -> f64` (method, since 0.4.0): Last time waking was retried. (seconds, negative infinity if not yet)
  - returns f64: Last time waking was retried. (wall clock seconds since the SoundSystem was created, f64::NEG_INFINITY if not yet)
- `pub fn read_muted(&self) -> bool` (method, since 0.4.0): Whether it should be muted now. (platform mute, the user's mute button, page hidden, window lost focus, takes precedence over the volume setting)
  - returns bool: True if any condition holds and it should be muted.
- `pub fn is_context_running(&self) -> bool` (method, since 0.4.0): Whether the AudioContext is running. (no sound plays if it is not)
  - returns bool: True if there is an AudioContext and it is running.
- `pub fn load_sounds(&mut self, engine: &Engine) -> SoundLoadHandle` (method, since 0.4.0): Loads sounds. (sound effects first, background music later, sounds that fail are skipped, already loaded ones are not loaded again, paths relative to the asset folder)
  - Calls update once at the end. (desktop opens the sound device at this point)
  - `engine` &Engine: Engine to resolve paths relative to the asset folder.
  - returns SoundLoadHandle: Handle that waits for all requested sound assets (including previously loaded ones). (awaiting it waits until all are loaded or fail)

  Example: If playback is requested before loading, it plays after loading

  ```rust
  use vanilla::{Engine, EngineConfiguration, SoundRow, SoundSystem};
  
  let engine = Engine::new(EngineConfiguration::new());
  let mut sound_system = SoundSystem::new(&engine, vec![SoundRow::create_music("field", "tests/assets/audio/vorbis_stereo.ogg", 0.6)]);
  sound_system.play_music("field", 0.0, false);
  sound_system.load_sounds(&engine);
  assert_eq!(sound_system.get_music_id(), "field");
  ```

- `pub fn wait_for_load(&self) -> SoundLoadFuture` (method, since 0.4.0): Future that waits for all requested sounds to finish. (in place of the await in the original await loadSounds(), await it inside an engine task after load_sounds)
  - Shares the sound assets held at the call, so it does not borrow the sound system. Sounds that fail are skipped. (not rejected, as in the original)
  - returns SoundLoadFuture: Future that finishes when the sound assets requested at call time have all loaded or failed. (finishes immediately if none are requested)

  Example: Finishes on the first poll when no sounds are requested

  ```rust
  use vanilla::{Engine, EngineConfiguration, SoundRow, SoundSystem};
  
  let engine = Engine::new(EngineConfiguration::new());
  let sound_system = SoundSystem::new(&engine, vec![SoundRow::create_effect("hit", &["tests/assets/audio/wav_s16_stereo.wav"], 1.0)]);
  let sound_load_future = sound_system.wait_for_load();
  let task_handle = engine.spawn_task(|_engine_context| async move {
  	sound_load_future.await;
  });
  assert!(task_handle.is_finished());
  ```

- `pub fn load_sound(&mut self, engine: &Engine, sound_row: &SoundRow)` (method, since 0.4.0): Loads one sound. (all of a group, ones that fail are left as None, reported and skipped)
  - Does not add it to the sound table. (play_effect, play_music only play ids in the table) Replaces anything already loaded under the same id.
  - `engine` &Engine: Engine to resolve paths relative to the asset folder.
  - `sound_row` &SoundRow: Sound row to load. (loads all of paths)
- `pub fn add_sound_asset(&mut self, sound_id: &str, audio_asset: Rc<AudioAsset>)` (method, since 0.4.0): Adds a sound asset directly. (for sounds not loaded from a file, like ones built in memory, appended to the recording group of the same id)
  - `sound_id` &str: Sound id to append to. (plays only if the sound table has a row for that id)
  - `audio_asset` Rc<AudioAsset>: Sound asset to add. (only loaded ones are picked)

  Example: Add a sound loaded from bytes in memory

  ```rust
  use std::rc::Rc;
  use vanilla::{AudioAsset, Engine, EngineConfiguration, SoundRow, SoundSystem};
  
  let engine = Engine::new(EngineConfiguration::new());
  let mut sound_system = SoundSystem::new(&engine, vec![SoundRow::create_effect("chime", &[], 1.0)]);
  let audio_asset = Rc::new(AudioAsset::new());
  let bytes = std::fs::read("tests/assets/audio/wav_s16_stereo.wav").unwrap();
  assert!(audio_asset.load_from_bytes(bytes).get_load_error().is_none());
  sound_system.add_sound_asset("chime", audio_asset);
  ```

- `pub fn set_music_volume(&mut self, music_volume: f64)` (method, since 0.4.0): Music volume setting. (0 ~ 1)
  - `music_volume` f64: Music volume. (clamped to 0 ~ 1, 0 if not a finite number)
- `pub fn set_music_scale(&mut self, music_scale: f64)` (method, since 0.4.0): Music ratio. (0 ~ 1, to lower it separately from the setting, such as half volume while the pause window is up)
  - `music_scale` f64: Ratio to multiply the music volume by. (clamped to 0 ~ 1, 0 if not a finite number)

  Example: Half volume while the pause window is open

  ```rust
  use vanilla::{Engine, EngineConfiguration, SoundSystem};
  
  let engine = Engine::new(EngineConfiguration::new());
  let mut sound_system = SoundSystem::new(&engine, Vec::new());
  sound_system.set_music_volume(0.8);
  sound_system.set_music_scale(0.5);
  assert_eq!(sound_system.get_music_volume(), 0.8);
  assert_eq!(sound_system.get_music_volume() * sound_system.get_music_scale(), 0.4);
  ```

- `pub fn set_sound_effect_volume(&mut self, sound_effect_volume: f64)` (method, since 0.4.0): Sound effect volume setting. (0 ~ 1)
  - `sound_effect_volume` f64: Sound effect volume. (clamped to 0 ~ 1, 0 if not a finite number)
- `pub fn set_user_muted(&mut self, is_user_muted: bool)` (method, since 0.4.0): The user's mute button. (music and sound effects at once)
  - `is_user_muted` bool: true mutes, false unmutes. (stays muted if another mute remains)
- `pub fn play_music(&mut self, sound_id: &str, fade_seconds: f64, is_resumed: bool)` (method, since 0.4.0): Plays background music. (loops, "" stops it, plays it then if not loaded yet or before the first press)
  - Over fade_seconds the previous music fades down and the new music rises from 0. (immediate if 0)
  - If is_resumed, the music continues from where it stopped. (otherwise from the start)
  - `sound_id` &str: Background music id to play. ("" turns it off, does nothing if it is the same as the one currently requested)
  - `fade_seconds` f64: Crossfade time. (seconds, 0 switches immediately, negative is treated as 0)
  - `is_resumed` bool: true resumes that music from where it stopped. (the stop position is remembered per sound)

  Example: Crossfade for 1 second when entering battle, and resume the field music from where it stopped when leaving

  ```rust
  use vanilla::SoundSystem;
  
  fn enter_battle(sound_system: &mut SoundSystem) {
  	sound_system.play_music("battle", 1.0, false);
  }
  
  fn leave_battle(sound_system: &mut SoundSystem) {
  	sound_system.play_music("field", 1.0, true);
  }
  ```

- `pub fn play_effect(&mut self, sound_id: &str, volume: f64, pan: f64)` (method, since 0.4.0): Plays a sound effect. (not played while muted, before the first press, before loading, or within the replay interval)
  - volume: volume this time. (0 ~ 1, multiplied by the sound volume and the effect volume setting)  pan: left and right. (-1 left ~ 1 right, 0 center)
  - `sound_id` &str: Sound effect id to play. (one in the sound table and already loaded)
  - `volume` f64: Volume for this play. (0 ~ 1, multiplied by the sound's volume and clamped to 0 ~ 1, not played if 0.001 or less)
  - `pan` f64: Pan. (-1 left ~ 1 right, 0 center, out of range is clamped, 0 if not a finite number)

  Example: Play a hit sound from the left of the screen at half volume

  ```rust
  use vanilla::SoundSystem;
  
  fn play_hit(sound_system: &mut SoundSystem) {
  	sound_system.play_effect("hit", 0.5, -0.8);
  }
  ```

- `pub fn fade_out_effects(&mut self, sound_id: &str, fade_seconds: f64)` (method, since 0.4.0): Fades out playing sound effects. (all sound effects if sound_id is "", cut immediately if the fade seconds are 0)
  - As in the original, fades from the current volume to 0 and removes it from the list. (even if a sound playing only its start is fading, it fades anew from the current volume)
  - `sound_id` &str: Sound effect id to fade out. ("" for all sound effects)
  - `fade_seconds` f64: Fade out time. (seconds, stops immediately if 0 or less or if there is no AudioContext)

  Example: Fade out all sound effects over 0.3 seconds when the scene changes

  ```rust
  use vanilla::SoundSystem;
  
  fn leave_stage(sound_system: &mut SoundSystem) {
  	sound_system.fade_out_effects("", 0.3);
  	assert_eq!(sound_system.get_effect_voice_count(), 0);
  }
  ```

- `pub fn stop_effects(&mut self)` (method, since 0.4.0): Cuts off all playing sound effects. (when the pause window opens, etc.)
- `pub fn get_effect_voice_count(&self) -> usize` (method, since 0.4.0): Number of playing sound effects. (excluding ones fading out)
  - returns usize: Number of sound effects playing. (update removes finished ones from the list)
- `pub fn update(&mut self)` (method, since 0.4.0): Every frame. (builds the sound path after the first press, follows the platform mute, plays background music, applies volumes)

## Functions and constants

- `pub fn set_sound_system(sound_system: Option<Rc<RefCell<SoundSystem>>>)` (method, since 0.4.0): Sets the shared sound. (None clears it)
  - `sound_system` Option<Rc<RefCell<SoundSystem>>>: Sound system to share. (None clears it, held separately per thread)

  Example: Set it and read it from elsewhere

  ```rust
  use std::cell::RefCell;
  use std::rc::Rc;
  use vanilla::{read_sound_system, set_sound_system, Engine, EngineConfiguration, SoundSystem};
  
  let engine = Engine::new(EngineConfiguration::new());
  let sound_system = Rc::new(RefCell::new(SoundSystem::new(&engine, Vec::new())));
  set_sound_system(Some(sound_system.clone()));
  if let Some(shared_sound_system) = read_sound_system() {
  	shared_sound_system.borrow_mut().set_sound_effect_volume(0.5);
  }
  assert_eq!(sound_system.borrow().get_sound_effect_volume(), 0.5);
  set_sound_system(None);
  assert!(read_sound_system().is_none());
  ```

- `pub fn read_sound_system() -> Option<Rc<RefCell<SoundSystem>>>` (method, since 0.4.0): The shared sound. (None if not yet)
  - returns Option<Rc<RefCell<SoundSystem>>>: Sound system set on this thread with set_sound_system. (None if not set or cleared)
