vanilladocs
vanillapunch.com
API / core/audiomanager

core/audiomanager

오디오 매니저.

  • 원본 core/audiomanager.js. 공유 AudioContext 를 들고 AudioPlayer 생성을 맡는다.
  • AudioContext 자리는 백엔드가 채운다. (platform/audio) 데스크탑: cpal 출력 위의 엔진 믹서(platform/audio/mixer.rs, 크롬 WebAudio 와 같은 셈). 처음 쓸 때 소리 장치를 연다. 멈추면(SoundSystem 음소거) 소리와 시계가 원본처럼 그 자리에서 선다. 웹: 원본과 같은 WebAudio AudioContext. 원본처럼 user gesture 뒤에 만들고, iOS 에서는 복원 뒤 시계를 확인한다.
  • 원본처럼 AudioContext 는 늦게 만든다. resume_context() 는 user gesture 전에는 아무것도 하지 않고, create_audio_player() 는 user gesture 전이라도 (마지못해) 만든다. 데스크탑에는 브라우저 자동재생 정책이 없어 처음부터 user gesture 가 있었던 것으로 둔다.
  • 원본과 다른 점: 상태를 Rc<RefCell> 로 나눠 든다. 웹의 시계 확인 타이머와 프로미스 콜백이 원본처럼 매니저를 다시 부르고, BeepPlayer 가 원본처럼 매니저를 참조로 들기 때문이다. 그래서 메서드는 모두 &self 로 부른다. (컴포넌트는 &Engine 만 받는다) AudioPlayer 는 원본처럼 만든 뒤 부른 쪽이 소유한다. 매니저는 만든 플레이어를 들고 있지 않는다. 원본 getAudioContext() 는 빌린 AudioContext(웹 WebAudio AudioContext, 데스크탑 엔진 믹서의 AudioContext, 둘 다 sample_rate()와 current_time() 이 있다)를 돌려준다. 없으면 None, has_audio_context() 도 있다. AudioManager 는 나눠 든 상태의 손잡이라 Clone 하면 같은 AudioContext 를 보는 손잡이가 하나 더 생긴다. (SoundSystem 이 원본처럼 매니저를 들 때) 생성자는 엔진을 받지 않는다. (원본은 iOS 판별에 엔진의 플랫폼 정보를 쓰고, 여기서는 웹 백엔드가 같은 규칙으로 직접 판별한다) create_audio_bus(원본 createAudioBus)는 AudioBus 를 만든다. 버스도 플레이어처럼 부른 쪽이 소유한다. create_audio_player 와 create_audio_bus 는 원본처럼 AudioPlayer::new(매니저, None), AudioBus::new(매니저) 와 같다.

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.

AudioManagerstruct traits Clone, Default

짝Counterpart: vanilla.js AudioManager소스source

오디오 매니저.

  • 엔진이 하나 들고, 씬과 컴포넌트는 engine.get_audio_manager() 로 빌려 플레이어와 버스를 만든다.

Audio manager.

  • The engine holds one, and scenes and components borrow it with engine.get_audio_manager() to create players and buses.
예제Example만든 직후에는 AudioContext 가 없다There is no AudioContext right after creation
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
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();
생성자constructorpub fn new() -> AudioManager#0.3.2 부터since 0.3.2소스source

생성. (AudioContext 는 아직 만들지 않는다)

Constructor. (does not create the AudioContext yet)

반환ReturnsAudioManager 새 오디오 매니저. (소리 장치는 플레이어나 버스를 처음 만들 때, 또는 user gesture 뒤 resume_context 에서 연다)New audio manager. (the sound device is opened when a player or bus is first created, or in resume_context after a user gesture)

짝Counterpart: vanilla.js AudioManager.constructor

메서드methodpub fn mark_user_gesture(&self)#0.3.2 부터since 0.3.2소스source

첫 user gesture 가 발생했음을 알린다. (Engine::resume_on_user_gesture 에서 부른다)

Signals that the first user gesture has occurred. (called from Engine::resume_on_user_gesture)

짝Counterpart: vanilla.js AudioManager.markUserGesture

메서드methodpub fn has_user_gesture(&self) -> bool#0.3.2 부터since 0.3.2소스source

user gesture 이후인지 여부. (데스크탑은 늘 참)

Whether a user gesture has occurred. (always true on desktop)

반환Returnsbool user gesture 가 있었으면 true. (웹은 mark_user_gesture 를 부르기 전까지 false)true if there has been a user gesture. (false on the web until mark_user_gesture is called)

짝Counterpart: vanilla.js AudioManager.hasUserGesture

메서드methodpub fn resume_context(&self)#0.3.2 부터since 0.3.2소스source

오디오 컨텍스트 재개.

  • user gesture 전에는 아무것도 하지 않는다.
  • 웹: "suspended" 나 "interrupted" 일 때만 resume() 하고, 거부는 조용히 넘긴다. iOS 는 복원 뒤 시계를 확인한다.
  • 데스크탑: 소리 장치를 아직 열지 않았으면 열고, 멈춰 두었으면 다시 돌린다.

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.

짝Counterpart: vanilla.js AudioManager.resumeContext

메서드methodpub fn create_audio_player(&self) -> AudioPlayer#0.3.2 부터since 0.3.2소스source

오디오 플레이어 생성. (AudioContext 가 없으면 만든다. 만들지 못하면 소리 없는 플레이어)

Creates an audio player. (creates the AudioContext if absent. A silent player if it cannot be created)

반환ReturnsAudioPlayer 출력으로 소리를 내는 새 플레이어. (부른 쪽이 소유하고, 버리면 소리도 멈춘다)New player that sends its sound to the output. (owned by the caller, dropping it also stops the sound)

짝Counterpart: vanilla.js AudioManager.createAudioPlayer

메서드methodpub fn create_audio_bus(&self) -> AudioBus#0.4.0 부터since 0.4.0소스source

오디오 버스 생성. (AudioContext 가 없으면 만든다. 만들지 못하면 소리 없는 버스)

Creates an audio bus. (creates the AudioContext if absent. A silent bus if it cannot be created)

반환ReturnsAudioBus 출력에 이은 새 버스. (부른 쪽이 소유한다)New bus connected to the output. (owned by the caller)

짝Counterpart: vanilla.js AudioManager.createAudioBus

예제Example배경음악 버스로 트는 플레이어A player that plays through the music bus
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);
}
메서드methodpub fn is_context_running(&self) -> bool#0.4.0 부터since 0.4.0소스source

AudioContext 가 있고 돌고 있는지. (SoundSystem 이 소리를 낼지 정할 때)

Whether the AudioContext exists and is running. (used by SoundSystem to decide whether to make sound)

반환Returnsbool AudioContext 가 있고 멈춰 있지 않으면 true. (웹은 state 가 "running" 일 때)true if the AudioContext exists and is not suspended. (on the web, when state is "running")

메서드methodpub fn get_context_time(&self) -> f64#0.4.0 부터since 0.4.0소스source

AudioContext 시계. (초, 원본 audioContext.currentTime, AudioContext 가 없으면 0)

AudioContext clock. (seconds, the original audioContext.currentTime, 0 if there is no AudioContext)

반환Returnsf64 AudioContext 를 만든 뒤 흐른 소리 시간. (초, AudioContext 가 없으면 0)Audio time elapsed since the AudioContext was created. (seconds, 0 if there is no AudioContext)

짝Counterpart: vanilla.js AudioManager.getContextTime

메서드methodpub fn get_audio_context(&self) -> Option<std::cell::Ref<'_, AudioContext>>#0.4.0 부터since 0.4.0소스source

AudioContext. (원본 getAudioContext, 아직 만들지 않았으면 None, 빌린 동안 매니저의 다른 함수를 부르지 않는다)

AudioContext. (the original getAudioContext, None if not yet created, do not call the manager's other functions while borrowed)

반환ReturnsOption<std::cell::Ref<'_, AudioContext>> 빌린 AudioContext. (아직 만들지 않았거나 만들지 못했으면 None)The borrowed AudioContext. (None if not yet created or if it could not be created)

짝Counterpart: vanilla.js AudioManager.getAudioContext

예제Example표본율 읽기 (빌린 것은 바로 놓는다)Read the sample rate (release the borrow right away)
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)
}
메서드methodpub fn has_audio_context(&self) -> bool#0.3.2 부터since 0.3.2소스source

AudioContext 가 만들어져 있는지. (원본 getAudioContext() !== null 자리)

Whether the AudioContext has been created. (in place of the original getAudioContext() !== null)

반환Returnsbool AudioContext 가 있으면 true.true if there is an AudioContext.