# core/audiomanager (vanilla-engine 0.4.0)

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

Audio manager.
- The original core/audiomanager.js. Holds the shared AudioContext and handles AudioPlayer creation.
- The backend fills the AudioContext slot. (platform/audio)
  Desktop: the engine mixer on top of cpal output (platform/audio/mixer.rs, same math as Chrome WebAudio). Opens the sound device on first use. When suspended (SoundSystem mute) the sound and the clock stop in place, as in the original.
  Web: a WebAudio AudioContext, same as the original. Created after a user gesture as in the original, and on iOS the clock is checked after resuming.
- As in the original, the AudioContext is created lazily. resume_context() does nothing before a user gesture,
  while create_audio_player() creates it (reluctantly) even before a user gesture.
  Desktop has no browser autoplay policy, so it is treated as having had a user gesture from the start.
- Differences from the original:
  State is shared through `Rc<RefCell>`. On the web the clock check timer and promise callbacks call back into the manager as in the original,
  and BeepPlayer holds the manager by reference as in the original. So all methods are called with &self. (components only receive &Engine)
  As in the original, an AudioPlayer is owned by the caller after creation. The manager does not hold the players it creates.
  The original getAudioContext() returns a borrowed AudioContext (the WebAudio AudioContext on the web, the engine mixer's AudioContext on desktop, both have sample_rate() and current_time()). None if absent, and has_audio_context() is also available.
  AudioManager is a handle to shared state, so cloning makes one more handle to the same AudioContext. (when SoundSystem holds the manager as in the original)
  The constructor does not take the engine. (the original uses the engine's platform info to detect iOS, here the web backend detects it directly with the same rule)
  create_audio_bus (the original createAudioBus) creates an AudioBus. Like players, buses are owned by the caller.
  create_audio_player and create_audio_bus are the same as AudioPlayer::new(manager, None) and AudioBus::new(manager), as in the original.

## AudioManager (struct) (Clone, Default)

Audio manager.
- The engine holds one, and scenes and components borrow it with engine.get_audio_manager() to create players and buses.

Example: There is no AudioContext right after creation

```rust
use vanilla::AudioManager;

let audio_manager = AudioManager::new();
assert!(!audio_manager.has_audio_context());
assert!(audio_manager.get_audio_context().is_none());
assert_eq!(audio_manager.get_context_time(), 0.0);
```

Example: Play a sound in a scene

```rust
use vanilla::{AudioPlayer, Engine, EngineConfiguration, Scene, SceneBase};

struct MainScene {
	scene_base: SceneBase,
	audio_player: Option<AudioPlayer>,
}

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 audio_asset = engine.load_audio_asset("tests/assets/audio/wav_s16_stereo.wav").unwrap();
		let mut audio_player = engine.get_audio_manager().create_audio_player();
		audio_player.set_audio_asset(audio_asset);
		audio_player.set_volume(0.5);
		audio_player.play(false);
		self.audio_player = Some(audio_player);
	}
}

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

- `pub fn new() -> AudioManager` (constructor, since 0.3.2): Constructor. (does not create the AudioContext yet)
  - returns AudioManager: New audio manager. (the sound device is opened when a player or bus is first created, or in resume_context after a user gesture)
- `pub fn mark_user_gesture(&self)` (method, since 0.3.2): Signals that the first user gesture has occurred. (called from Engine::resume_on_user_gesture)
- `pub fn has_user_gesture(&self) -> bool` (method, since 0.3.2): Whether a user gesture has occurred. (always true on desktop)
  - returns bool: true if there has been a user gesture. (false on the web until mark_user_gesture is called)
- `pub fn resume_context(&self)` (method, since 0.3.2): Resumes the audio context.
  - Does nothing before a user gesture.
  - Web: calls resume() only when "suspended" or "interrupted", and silently ignores rejection. On iOS the clock is checked after resuming.
  - Desktop: opens the sound device if not yet open, and restarts it if suspended.
- `pub fn create_audio_player(&self) -> AudioPlayer` (method, since 0.3.2): Creates an audio player. (creates the AudioContext if absent. A silent player if it cannot be created)
  - returns AudioPlayer: New player that sends its sound to the output. (owned by the caller, dropping it also stops the sound)
- `pub fn create_audio_bus(&self) -> AudioBus` (method, since 0.4.0): Creates an audio bus. (creates the AudioContext if absent. A silent bus if it cannot be created)
  - returns AudioBus: New bus connected to the output. (owned by the caller)

  Example: A player that plays through the music bus

  ```rust
  use vanilla::Engine;
  
  fn play_music(engine: &Engine) {
  	let music_bus = engine.get_audio_manager().create_audio_bus();
  	music_bus.set_volume(0.6);
  	let mut music_player = music_bus.create_audio_player();
  	let audio_asset = engine.load_audio_asset("tests/assets/audio/vorbis_stereo.ogg").unwrap();
  	music_player.set_audio_asset(audio_asset);
  	music_player.play(true);
  }
  ```

- `pub fn is_context_running(&self) -> bool` (method, since 0.4.0): Whether the AudioContext exists and is running. (used by SoundSystem to decide whether to make sound)
  - returns bool: true if the AudioContext exists and is not suspended. (on the web, when state is "running")
- `pub fn get_context_time(&self) -> f64` (method, since 0.4.0): AudioContext clock. (seconds, the original audioContext.currentTime, 0 if there is no AudioContext)
  - returns f64: Audio time elapsed since the AudioContext was created. (seconds, 0 if there is no AudioContext)
- `pub fn get_audio_context(&self) -> Option<std::cell::Ref<'_, AudioContext>>` (method, since 0.4.0): AudioContext. (the original getAudioContext, None if not yet created, do not call the manager's other functions while borrowed)
  - returns Option<std::cell::Ref<'_, AudioContext>>: The borrowed AudioContext. (None if not yet created or if it could not be created)

  Example: Read the sample rate (release the borrow right away)

  ```rust
  use vanilla::AudioManager;
  
  fn read_sample_rate(audio_manager: &AudioManager) -> Option<f64> {
  	let audio_context = audio_manager.get_audio_context()?;
  	Some(audio_context.sample_rate() as f64)
  }
  ```

- `pub fn has_audio_context(&self) -> bool` (method, since 0.3.2): Whether the AudioContext has been created. (in place of the original getAudioContext() !== null)
  - returns bool: true if there is an AudioContext.
