# core/soundsystem (vanilla.js 0.4.0)

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

Sound. (background music and sound effects)

Uses the engine's AudioManager (shared AudioContext) and AudioAsset (MP3). Plays downloaded sound buffers with Web Audio. (does not synthesize sound, only plays files)
Takes a sound table. Each row is { id, path or paths, volume, minimumInterval, isMusic, maximumVoices, pitchVariation, playSeconds, fadeOutSeconds }.
  volume: per-sound volume. (0 ~ 1, 1 if absent)  minimumInterval: interval before the same sound can play again. (seconds, so they do not pile up and get noisy)
  paths: a group of multiple recordings of the same sound. Picks one each time it plays, never the same as the one just before. (path if only one)
  maximumVoices: number of instances of the same sound that can play at once. (beyond that the oldest is cut off, if absent up to the total number of sound effects)
  pitchVariation: ratio by which the pitch varies on each play. (0.05 means ±5%, 0 if absent)
  playSeconds, fadeOutSeconds: plays only the first playSeconds seconds of a sound effect and fades it out over fadeOutSeconds seconds. (long files, to the end if absent or 0)
  loadType: load type. (AudioLoadType, background music uses streaming and sound effects use decompressOnLoad if absent, sound effects overlap so they must be fully decompressed to play)

Volume: background music = music volume setting × music ratio (half volume for the pause window, etc.) × sound volume, sound effect = sound effect volume setting × sound volume × volume at call time (attenuation by distance, etc.).
Background music can be crossfaded (fadeSeconds), and the stopped position is remembered per sound so it can resume from there. (isResumed)
Mute takes precedence over the volume setting. If any one of the following applies, no sound plays regardless of the settings.
  - Platform mute. (the function given with setExternalMuteProvider, the platform SDK's mute setting, while a rewarded ad is shown, etc.)
  - The user's mute button. (setUserMuted)
  - Page hidden. (another tab, app switch)
  - The window loses focus on a touch-primary device. (blur, when the app starts going to the background)
    On iPhone the page-hidden notification arrives after the app has gone to the background, by which time audio freezes without stopping and the last sound chunk repeats.
    The window focus-loss notification arrives before that. On desktop, clicking outside the canvas (the outer page) also loses focus, so it is not followed there.
Platform mute is read every frame (update), and page hiding is applied at that moment. (frames stop when hidden)
While muted, the AudioContext is also stopped. (suspend, resume when unmuted) On iPhone, if an app switch or interstitial ad takes over a running AudioContext,
no sound plays even when it is woken on return. If it is stopped on its own beforehand, sound plays again on return.
If the AudioContext is still not running after unmuting, it tries to wake it at short intervals until it runs. (iPhone sometimes ignores the wake at the moment of returning to the app)

If allowed (setAutoplayAllowedProvider, allowed if not given), it tries to wake once even before a press. If blocked, it turns on at the first press as below.
Browsers do not allow sound before the person first presses. Since the engine creates and wakes the AudioContext on the first press,
the sound paths (music and sound effect buses, AudioBus) are created after that, and sound plays only while the AudioContext is running. (so sounds requested while stopped do not all play at once on wake)
Buses are retrieved with getMusicBus and getEffectBus. Players made from a bus (AudioBus.createAudioPlayer) also follow the volume setting and mute.
The volume setting is applied directly to the bus's GainNode. So values set with the bus's setVolume and mute last only until SoundSystem applies the volume again.
Sound files are downloaded in the background so they do not block play. Sounds not yet downloaded or that failed to download simply do not play.

## SoundSystem

Sound. (background music and sound effects)

Uses the engine's AudioManager (shared AudioContext) and AudioAsset (MP3). Plays downloaded sound buffers with Web Audio. (does not synthesize sound, only plays files)
Takes a sound table. Each row is { id, path or paths, volume, minimumInterval, isMusic, maximumVoices, pitchVariation, playSeconds, fadeOutSeconds }.
  volume: per-sound volume. (0 ~ 1, 1 if absent)  minimumInterval: interval before the same sound can play again. (seconds, so they do not pile up and get noisy)
  paths: a group of multiple recordings of the same sound. Picks one each time it plays, never the same as the one just before. (path if only one)
  maximumVoices: number of instances of the same sound that can play at once. (beyond that the oldest is cut off, if absent up to the total number of sound effects)
  pitchVariation: ratio by which the pitch varies on each play. (0.05 means ±5%, 0 if absent)
  playSeconds, fadeOutSeconds: plays only the first playSeconds seconds of a sound effect and fades it out over fadeOutSeconds seconds. (long files, to the end if absent or 0)
  loadType: load type. (AudioLoadType, background music uses streaming and sound effects use decompressOnLoad if absent, sound effects overlap so they must be fully decompressed to play)

Volume: background music = music volume setting × music ratio (half volume for the pause window, etc.) × sound volume, sound effect = sound effect volume setting × sound volume × volume at call time (attenuation by distance, etc.).
Background music can be crossfaded (fadeSeconds), and the stopped position is remembered per sound so it can resume from there. (isResumed)
Mute takes precedence over the volume setting. If any one of the following applies, no sound plays regardless of the settings.
  - Platform mute. (the function given with setExternalMuteProvider, the platform SDK's mute setting, while a rewarded ad is shown, etc.)
  - The user's mute button. (setUserMuted)
  - Page hidden. (another tab, app switch)
  - The window loses focus on a touch-primary device. (blur, when the app starts going to the background)
    On iPhone the page-hidden notification arrives after the app has gone to the background, by which time audio freezes without stopping and the last sound chunk repeats.
    The window focus-loss notification arrives before that. On desktop, clicking outside the canvas (the outer page) also loses focus, so it is not followed there.
Platform mute is read every frame (update), and page hiding is applied at that moment. (frames stop when hidden)
While muted, the AudioContext is also stopped. (suspend, resume when unmuted) On iPhone, if an app switch or interstitial ad takes over a running AudioContext,
no sound plays even when it is woken on return. If it is stopped on its own beforehand, sound plays again on return.
If the AudioContext is still not running after unmuting, it tries to wake it at short intervals until it runs. (iPhone sometimes ignores the wake at the moment of returning to the app)

If allowed (setAutoplayAllowedProvider, allowed if not given), it tries to wake once even before a press. If blocked, it turns on at the first press as below.
Browsers do not allow sound before the person first presses. Since the engine creates and wakes the AudioContext on the first press,
the sound paths (music and sound effect buses, AudioBus) are created after that, and sound plays only while the AudioContext is running. (so sounds requested while stopped do not all play at once on wake)
Buses are retrieved with getMusicBus and getEffectBus. Players made from a bus (AudioBus.createAudioPlayer) also follow the volume setting and mute.
The volume setting is applied directly to the bus's GainNode. So values set with the bus's setVolume and mute last only until SoundSystem applies the volume again.
Sound files are downloaded in the background so they do not block play. Sounds not yet downloaded or that failed to download simply do not play.

Example: Play sound effects and background music from a sound table

```js
import { Engine, EngineConfiguration, Scene, SoundSystem, setSoundSystem, readSoundSystem } from "./build/vanilla.js";

class MainScene extends Scene {
	tick(timeDelta) {
		super.tick(timeDelta);
		const soundSystem = readSoundSystem();
		if (soundSystem !== null) {
			soundSystem.update();
		}
	}
}

const engineConfiguration = new EngineConfiguration();
const engine = new Engine(engineConfiguration);
const audioManager = engine.getAudioManager();
const soundSystem = new SoundSystem(audioManager, [
	{ id: "beep", path: "examples/assets/beep.wav", volume: 1, minimumInterval: 0.05, maximumVoices: 4, pitchVariation: 0.05 },
	{ id: "music", path: "examples/assets/beep.wav", volume: 0.6, isMusic: true },
]);
setSoundSystem(soundSystem);
soundSystem.setSoundEffectVolume(0.8);
soundSystem.setMusicVolume(0.5);
await soundSystem.loadSounds();
soundSystem.playMusic("music", 0.5);
soundSystem.playEffect("beep", 0.5, -0.3);
console.log(soundSystem.getMusicId(), soundSystem.getEffectVoiceCount());
engine.run(new MainScene());
```

- `constructor(audioManager, soundTable)` (constructor, since 0.4.0): Constructor.
  - `audioManager` object: The engine's AudioManager (engine.getAudioManager())
  - `soundTable` object[]: [{ id, path or paths, volume, minimumInterval, isMusic, maximumVoices, pitchVariation, playSeconds, fadeOutSeconds }]
- `addSounds(soundTable)` (method, since 0.4.0): Adds rows to the sound table. (same id replaces, downloading is done by loadSounds)
  - `soundTable` object[]: List of sound table rows. (same form as the constructor's soundTable)
- `addSoundAsset(soundId, audioAsset)` (method, since 0.4.0): Adds a sound asset directly. (for sounds not downloaded from a file, such as sounds built in memory, appended to the recording group of the same id)
  - Volume and interval follow the row of the same id in the sound table (addSounds). (does not play if there is no row) Downloading (loadSounds) does not download this id again.
  - `soundId` string: Sound table id.
  - `audioAsset` AudioAsset: Audio asset already loaded. (appended to the end of that id's take group)

  Example: Hook a sound not fetched from a file into the sound table

  ```js
  import { Engine, EngineConfiguration, AudioAsset, SoundSystem } from "./build/vanilla.js";
  
  const engineConfiguration = new EngineConfiguration();
  const engine = new Engine(engineConfiguration);
  const audioManager = engine.getAudioManager();
  const soundSystem = new SoundSystem(audioManager, []);
  const response = await fetch("examples/assets/beep.wav");
  const bytes = await response.arrayBuffer();
  const audioAsset = new AudioAsset();
  await audioAsset.loadFromBytes(bytes);
  soundSystem.addSounds([{ id: "generated", volume: 1 }]);
  soundSystem.addSoundAsset("generated", audioAsset);
  soundSystem.update();
  soundSystem.playEffect("generated");
  ```

- `setExternalMuteProvider(externalMuteProvider)` (method, since 0.4.0): Sets the function that reads external mute. (platform SDK mute, while a rewarded ad is shown, etc., read every frame, null for none)
  - `externalMuteProvider` function(): boolean | null: Function that mutes when it returns true. (null if none)

  Example: Mute sound while an ad is showing

  ```js
  import { Engine, EngineConfiguration, SoundSystem } from "./build/vanilla.js";
  
  const engineConfiguration = new EngineConfiguration();
  const engine = new Engine(engineConfiguration);
  const audioManager = engine.getAudioManager();
  const soundSystem = new SoundSystem(audioManager, []);
  let isAdvertisementShowing = false;
  soundSystem.setExternalMuteProvider(() => {
  	return isAdvertisementShowing;
  });
  isAdvertisementShowing = true;
  soundSystem.update();
  console.log(soundSystem.readMuted());
  ```

- `getExternalMuteProvider()` (method, since 0.4.0): Returns the function that reads external mute.
  - returns function(): boolean | null: Function that reads the external mute. (null if none)
- `setAutoplayAllowedProvider(autoplayAllowedProvider)` (method, since 0.4.0): Sets the function that reads whether waking before a press is allowed. (a function returning false on platforms where the webview blocks it, null means allowed)
  - `autoplayAllowedProvider` function(): boolean | null: Function that returns true if waking before the first press is allowed. (allowed if null)
- `getAutoplayAllowedProvider()` (method, since 0.4.0): Returns the function that reads whether waking before a press is allowed.
  - returns function(): boolean | null: Function that reads whether waking before the first press is allowed. (null if none)
- `getAudioManager()` (method, since 0.4.0): Returns the engine's AudioManager. (the one passed to the constructor)
  - returns object: The engine's AudioManager.
- `getMusicBus()` (method, since 0.4.0): Background music and sound effect buses. (null before the first press)
  - returns AudioBus | null: Background music bus. (null before the first press)
- `getEffectBus()` (method, since 0.4.0): Sound effect bus. (null before the first press)
  - returns AudioBus | null: Sound effect bus. (null before the first press)
- `getMusicId()` (method, since 0.4.0): Background music requested to play. ("" if none)
  - returns string: Requested background music id. ("" if none)
- `getMusicVolume()` (method, since 0.4.0): Music volume setting.
  - returns number: Music volume. (0 ~ 1, default 1)
- `getMusicScale()` (method, since 0.4.0): Music ratio. (half volume for the pause window, etc.)
  - returns number: Music scale. (0 ~ 1, default 1)
- `getSoundEffectVolume()` (method, since 0.4.0): Sound effect volume setting.
  - returns number: Sound effect volume. (0 ~ 1, default 1)
- `isUserMuted()` (method, since 0.4.0): Whether the user's mute button is pressed.
  - returns boolean: True if the user muted.
- `isPageHidden()` (method, since 0.4.0): Whether the page is hidden.
  - returns boolean: True if the page is hidden.
- `isBlurMuteEnabled()` (method, since 0.4.0): Whether to mute when the window loses focus. (touch-primary devices)
  - returns boolean: True on a device that mutes when the window loses focus. (pointer: coarse)
- `isWindowBlurred()` (method, since 0.4.0): Whether the window has lost focus. (true only on devices that mute)
  - returns boolean: True if the window lost focus.
- `isContextPaused()` (method, since 0.4.0): Whether the AudioContext has been stopped due to mute.
  - returns boolean: True if the AudioContext was suspended for muting.
- `getLastContextResumeTime()` (method, since 0.4.0): Last time a wake was attempted. (seconds)
  - returns number: Last time a wake was retried. (seconds, based on performance.now, negative infinity if never)
- `readMuted()` (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 boolean: True if it should be muted.
- `isContextRunning()` (method, since 0.4.0): Whether the AudioContext is running. (no sound plays if it is not)
  - returns boolean: True if there is an AudioContext and it is "running".
- `async loadSounds()` (method, since 0.4.0): Downloads sounds. (sound effects first, together, large background music later, skips sounds that fail, does not redownload ones already downloaded)
- `async loadSound(soundRow)` (method, since 0.4.0): Downloads one sound. (all of a group, leaves failures as null and skips them)
  - `soundRow` object: Sound table row.
- `setMusicVolume(volume)` (method, since 0.4.0): Music volume setting. (0 ~ 1)
  - `volume` number: Music volume. (clamped to 0 ~ 1, 0 if not a number)
- `setMusicScale(scale)` (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)
  - `scale` number: Music scale. (clamped to 0 ~ 1, 0 if not a number)
- `setSoundEffectVolume(volume)` (method, since 0.4.0): Sound effect volume setting. (0 ~ 1)
  - `volume` number: Sound effect volume. (clamped to 0 ~ 1, 0 if not a number)
- `setUserMuted(isMuted)` (method, since 0.4.0): The user's mute button. (music and sound effects at once)
  - `isMuted` boolean: True to mute. (values other than true count as false)
- `playMusic(soundId, fadeSeconds = 0, isResumed = false)` (method, since 0.4.0): Plays background music. (loops, "" stops it, if before downloading or before the first press it plays then)
    - Over fadeSeconds the previous music fades down and the new music rises from 0. (immediately if 0)
    - If isResumed, resumes that music from where it stopped. (otherwise from the start)
  - `soundId` string: Background music id in the sound table. ("" turns it off, does nothing if it equals the currently requested one)
  - `fadeSeconds` number: Crossfade time. (seconds, default 0, negative becomes 0)
  - `isResumed` boolean: If true, resumes that music from where it stopped. (default false)
- `playEffect(soundId, volume = 1, pan = 0)` (method, since 0.4.0): Plays a sound effect. (does not play if muted, before the first press, before downloading, or within the replay interval)
  - `soundId` string: Sound effect id in the sound table. (not played if missing from the table or not fetched)
  - `volume` number: Volume for this call. (0 ~ 1, multiplied by the sound volume and the sound effect volume setting)
  - `pan` number: Pan. (-1 left ~ 1 right, 0 center)
- `pickVariant(soundId, assets)` (method, since 0.4.0): Picks one from a group. (a downloaded one different from the one just before, that one if only one, null if none)
  - `soundId` string: Sound table id. (key that remembers the index picked just before)
  - `assets` Array<AudioAsset | null>: Take group. (entries that failed to fetch are null)
  - returns AudioAsset | null: The picked asset. (null if none were fetched)
- `trimVoices(soundId, keepCount)` (method, since 0.4.0): Reduces playing sound effects to that count. (cuts off the oldest first, all sound effects if soundId is "")
  - `soundId` string: Sound effect id to reduce. ("" means all sound effects)
  - `keepCount` number: Number to keep. (negative becomes 0)
- `stopVoice(voice)` (method, since 0.4.0): Cuts off one sound effect.
  - `voice` object: A playing sound effect. ({ soundId, source, gainNode, startTime })
- `fadeOutEffects(soundId, fadeSeconds)` (method, since 0.4.0): Fades out playing sound effects. (all sound effects if soundId is "", cuts off immediately if the fade seconds are 0)
  - `soundId` string: Sound effect id to reduce. ("" means all sound effects)
  - `fadeSeconds` number: Fade time. (seconds, cuts at once if 0 or less)
- `getEffectVoiceCount()` (method, since 0.4.0): Number of sound effects playing. (for tests and logging)
  - returns number: Number of playing sound effects.
- `stopEffects()` (method, since 0.4.0): Cuts off all playing sound effects. (when the pause window opens, etc.)
- `update()` (method, since 0.4.0): Every frame. (creates the sound paths after the first press, follows platform mute, plays background music)
- `retryContextResume()` (method, since 0.4.0): Tries waking again. (every CONTEXT_RESUME_RETRY_INTERVAL when not muted but the AudioContext is not running)
  On iPhone, resume() called at the moment of returning to the app (visible again) is sometimes ignored because audio has not come back yet.
  After that, touches that only drag do not count as a human press, so no sound played until a button was pressed.
  The case where it reports running after waking but no sound plays (the clock is stopped) is checked on iOS by the engine's AudioManager. (engine v0.3.2, iOS 26.6.2 update fix)
- `tryAutoplay()` (method, since 0.4.0): Tries waking before a press. (once at first when the platform allows, if the webview blocks it the AudioContext stays stopped and the engine wakes it on the first press)
- `ensurePlayers()` (method, since 0.4.0): Creates the sound paths. (once after the first press, so the AudioContext is not created before then)
    - The engine creates the AudioContext when creating a bus.
- `applyVolumes()` (method, since 0.4.0): Applies volume. (0 if muted)
- `applyMute()` (method, since 0.4.0): Applies mute. (only when it changes, cuts off playing sound effects when muted)
- `applyContextPause()` (method, since 0.4.0): Stops the AudioContext while muted and wakes it when unmuted. (only when it changes, not done before the first press since there is no AudioContext)
- `updateMusic()` (method, since 0.4.0): Plays and switches background music. (only when the AudioContext is running and it is downloaded, runs silently even while muted so it is heard continuing when unmuted)
    - When asked to switch, the previous music starts fading down at once (remembering where it stopped), and the new music rises from 0 if downloaded.
- `fadeOutMusic(playingMusic, fadeSeconds)` (method, since 0.4.0): Fades out the playing background music. (over fadeSeconds, remembering the position when fully faded)
  - `playingMusic` object: The background music that was playing. ({ soundId, source, player, gain, startTime, offset, duration })
  - `fadeSeconds` number: Fade time. (seconds, turns off at once if 0)

## Functions and constants

- `setSoundSystem(soundSystem)` (method, since 0.4.0): Sets the shared sound.
  - `soundSystem` SoundSystem: Sound to share. (clears it if null)
- `readSoundSystem()` (method, since 0.4.0): Shared sound. (null if none yet)
  - returns SoundSystem | null: The shared sound. (null before setSoundSystem)
