core/soundsystem
소리 표로 다루는 배경음악과 효과음. (vanilla.js core/soundsystem.js 의 SoundSystem)
- AudioManager 와 AudioAsset 을 쓴다. 소리를 합성하지 않고 파일만 튼다.
- 소리 표의 줄마다 SoundRow { id, paths, volume, minimum_interval, is_music, maximum_voices, pitch_variation, play_seconds, fade_out_seconds, load_type }. paths: 같은 소리를 여러 번 녹음한 무리. 낼 때마다 받아 둔 것 가운데 하나를 고르고 바로 앞과 같은 것은 고르지 않는다. minimum_interval: 같은 소리를 다시 낼 수 있는 간격. (초, 한꺼번에 몰려 시끄럽지 않게) maximum_voices: 같은 소리가 한꺼번에 날 수 있는 수. (넘으면 가장 오래된 것을 끊는다, None 이면 효과음 전체의 수까지, 0 이면 원본처럼 하나) pitch_variation: 낼 때마다 음 높이를 흔드는 비. (0.05 면 ±5%) play_seconds, fade_out_seconds: 효과음을 앞의 play_seconds 초만 틀고 fade_out_seconds 초 동안 줄여 끈다. (0 이면 끝까지) load_type: 읽기 방식. (AudioLoadType, None 이면 배경음악은 Streaming, 효과음은 DecompressOnLoad, 효과음은 겹쳐 트므로 통째로 풀어야 난다)
- 크기: 배경음악 = 음악 크기 × 음악의 비 × 소리의 크기, 효과음 = 효과음 크기 × 소리의 크기 × 부를 때의 크기. 음악과 효과음의 크기는 버스(get_music_bus, get_effect_bus 의 AudioBus)에 걸고, 바꿀 때 0.05 초를 시간 상수로 따라간다. (원본 setTargetAtTime) 버스는 첫 누름 뒤에 만든다. (그 전에는 None) 버스로 만든 플레이어(AudioBus::create_audio_player)도 설정 크기와 음소거를 따른다.
- 배경음악은 틀어 달라고 한 것(get_music_id)을 기억해 두고, 받기 전이거나 첫 누름 전이면 그때 튼다. ("" 이면 끈다) 겹쳐 바꿀 수 있고(fade_seconds), 멈췄던 자리를 소리마다 기억해 이어 틀 수 있다. (is_resumed) 첫 파일을 받지 못했으면 틀지 않는다.
- 음소거는 설정한 크기보다 먼저다. 아래 가운데 하나라도 맞으면 소리가 나지 않는다. 바깥의 음소거(set_external_mute_provider, 플랫폼 SDK 나 광고), 사용자의 음소거(set_user_muted), 페이지가 가려짐(다른 탭, 앱 전환), 터치가 주된 기기에서 창이 포커스를 잃음(blur). 아이폰은 페이지가 가려졌다는 알림이 앱이 내려간 뒤에 와서 오디오가 멈추지 못한 채 얼어 마지막 소리 조각이 되풀이되는데, 포커스를 잃는 알림은 그보다 먼저 온다. 데스크탑(마우스)은 캔버스 바깥을 누를 때도 포커스를 잃어 따르지 않는다. 포커스가 돌아오거나 화면을 누르거나 페이지가 다시 보이면 풀린다.
- 음소거인 동안은 AudioContext 도 멈춘다. (풀리면 깨운다) 아이폰은 돌던 AudioContext 를 앱 전환이나 전면 광고가 가로채면 돌아와서 깨워도 소리가 나지 않아, 그 전에 스스로 멈춰 둔다. 풀린 뒤에도 돌지 않으면 0.5 초마다 다시 깨워 본다.
- 허락하면(set_autoplay_allowed_provider, 주지 않으면 허락) 누르기 전에도 첫 update 에서 한 번 깨워 본다. 막히면 엔진이 첫 누름에 깨운다. 첫 누름(user gesture) 전이거나 AudioContext 가 돌지 않을 때는 효과음을 내지 않는다. (멈춘 동안 부른 소리가 깨어날 때 한꺼번에 나지 않게)
- 소리 파일은 놀이를 막지 않게 뒤에서 받는다. (웹은 디코딩이 끝나면 난다) 못 받은 소리는 나지 않을 뿐이다.
- 시각: 같은 소리 간격과 다시 깨우기 간격은 원본 performance.now() 처럼 벽시계(web_time::Instant), 크기 따라가기와 줄이기, 음악의 멈춘 자리는 원본처럼 AudioContext 시계(AudioManager::get_context_time)로 센다.
- 함께 쓰는 소리: set_sound_system, read_sound_system. (원본 모듈 변수, 스레드 하나에 하나)
- 원본과 다른 것:
- 만들 때 AudioManager 대신 엔진을 받는다. 원본은 document 와 window 에 리스너를 다는데, 러스트 판은 엔진의 페이지 이벤트(PageEvent)로 받기 때문이다. 이벤트가 온 그 자리에서는 AudioContext 를 멈추거나 깨우고(소리가 바로 멎는다), 효과음 끊기는 다음 update 에서 한다.
- load_sounds, load_sound 는 애셋 폴더 기준 경로를 풀 엔진을 받는다. (원본은 브라우저가 페이지 주소로 푼다) 데스크탑은 그 자리에서 읽는다. load_sounds 는 원본처럼 await 할 수 있는 SoundLoadHandle 을 돌려준다. (걸어 둔 소리를 다 받거나 실패할 때까지 기다린다, wait_for_load().await 도 같다)
- 크기 바꾸기와 줄이기는 원본처럼 GainNode 의 AudioParam 자동화(value 대입, setValueAtTime, linearRampToValueAtTime, setTargetAtTime, cancelScheduledValues)와 source.stop(when)으로 소리 장치에 맡긴다. 웹은 WebAudio 에, 데스크탑은 믹서(크로미엄과 같은 셈)에 건다. 원본 { source, gainNode } 자리는 버스로 만든 AudioPlayer 하나이고, 끝난 소리(원본 onended)는 update 에서 목록에서 뺀다. 원본처럼 버스의 set_volume, mute 로 건 값은 SoundSystem 이 크기를 다시 걸 때까지 간다.
- 무리에서 고르기와 음 높이 흔들기는 원본 Math.random 자리인 엔진 math::random(처음 쓸 때 시각으로 씨앗을 정한다)을 쓴다.
- add_sound_asset(파일로 받지 않는 소리 더하기)과 get_effect_voice_count 는 러스트 판에서 먼저 만들었다. (원본에도 같은 이름으로 넣었다)
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)
SoundLoadHandlestruct traits Clone, Debug, std::future::IntoFuture
소리 받기 손잡이. (SoundSystem::load_sounds 가 돌려준다. 원본 loadSounds 의 Promise 자리, 걸어 둔 소리 애셋을 나눠 든다)
- 그대로 await 하면 걸어 둔 소리를 다 받거나 실패할 때까지 기다린다. (못 받은 소리는 건너뛰고, 돌려주는 값은 없다)
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)
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);
});SoundLoadFuturestruct traits Clone, Debug, std::future::Future
소리 받기를 기다리는 퓨처. (다 받거나 실패할 때까지, 원본처럼 못 받은 소리는 건너뛴다)
- SoundLoadHandle 을 await 하거나 SoundSystem::wait_for_load 가 돌려준다. 엔진 작업 안에서 await 한다.
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.
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());SoundRowstruct traits Clone, Debug
소리 표의 한 줄.
- create_effect, create_music 으로 만들고 나머지 칸은 필드에 바로 쓴다.
One row of the sound table.
- Create with create_effect, create_music and write the other fields directly.
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);효과음 한 줄. (나머지 칸은 기본)
One sound effect row. (other fields default)
- id&str
- 소리 이름.Sound name.
- paths&[&str]
- 같은 소리를 녹음한 파일 경로들. (애셋 폴더 기준)File paths recording the same sound. (relative to the asset folder)
- volumef64
- 소리의 크기. (0 ~ 1)Sound volume. (0 ~ 1)
반환ReturnsSoundRow 효과음 줄. (minimum_interval, pitch_variation, play_seconds, fade_out_seconds 는 0, maximum_voices 와 load_type 은 None)Sound effect row. (minimum_interval, pitch_variation, play_seconds, fade_out_seconds are 0, maximum_voices and load_type are None)
배경음악 한 줄.
One background music row.
- id&str
- 소리 이름.Sound name.
- path&str
- 음악 파일 경로. (애셋 폴더 기준)Music file path. (relative to the asset folder)
- volumef64
- 소리의 크기. (0 ~ 1)Sound volume. (0 ~ 1)
반환ReturnsSoundRow 배경음악 줄. (is_music 이 true, 경로 하나, 나머지 칸은 create_effect 와 같다)Background music row. (is_music is true, one path, other fields same as create_effect)
소리 이름. (play_effect, play_music 에 넘기는 id)
Sound name. (the id passed to play_effect, play_music)
반환ReturnsString
같은 소리를 여러 번 녹음한 무리의 파일 경로. (애셋 폴더 기준, 효과음은 낼 때마다 받아 둔 것 가운데 바로 앞과 다른 것을 고르고, 배경음악은 첫 파일만 튼다)
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)
반환ReturnsVec<String>
소리의 크기. (0 ~ 1, 효과음은 부를 때의 크기와 곱한 뒤 0 ~ 1 로 다듬는다)
Sound volume. (0 ~ 1, sound effects multiply it by the volume at the call then clamp to 0 ~ 1)
반환Returnsf64
같은 효과음을 다시 낼 수 있는 간격. (초, 0 이면 막지 않는다)
Interval before the same sound effect can play again. (seconds, 0 does not block)
반환Returnsf64
배경음악 줄인지. (load_sounds 가 효과음을 먼저, 배경음악을 나중에 받는다)
Whether it is a background music row. (load_sounds loads sound effects first and background music later)
반환Returnsbool
같은 효과음이 한꺼번에 날 수 있는 수. (넘으면 가장 오래된 것을 끊는다, None 이면 효과음 전체의 수 12 까지, 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)
반환ReturnsOption<usize>
낼 때마다 음 높이를 흔드는 비. (0.05 면 ±5%, 0 이면 흔들지 않는다)
Ratio by which the pitch wobbles each time it plays. (0.05 means ±5%, 0 means no wobble)
반환Returnsf64
효과음을 앞에서부터 틀 시간. (초, 0 이면 끝까지)
Time to play the sound effect from the start. (seconds, 0 means to the end)
반환Returnsf64
play_seconds 뒤에 줄여 끄는 시간. (초, play_seconds 가 0 이면 쓰지 않는다)
Time to fade out after play_seconds. (seconds, unused if play_seconds is 0)
반환Returnsf64
읽기 방식. (None 이면 배경음악은 Streaming, 효과음은 DecompressOnLoad, 원본 소리 표의 loadType)
Load type. (None means Streaming for background music and DecompressOnLoad for sound effects, the original sound table loadType)
반환ReturnsOption<AudioLoadType>
SoundSystemstruct
소리 표로 다루는 배경음악과 효과음. (원본 SoundSystem, 엔진의 AudioManager 를 나눠 들고 페이지 이벤트로 음소거한다)
- 매 프레임 update 를 부른다. 버스는 첫 누름 뒤의 update 에서 만든다.
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.
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(), "");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();생성. (소리 표를 받는다, 받기는 load_sounds 가 한다, 창이 포커스를 잃으면 음소거할지는 지금의 주된 손으로 정한다)
- 엔진의 AudioManager 를 나눠 들고 페이지 이벤트 리스너를 단다.
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
- AudioManager 를 나눠 주고 페이지 이벤트를 보낼 엔진. (페이지가 가려졌는지도 여기서 읽는다)Engine that shares the AudioManager and sends page events. (whether the page is hidden is also read from here)
- sound_tableVec<SoundRow>
- 소리 표. (같은 id 는 뒤의 줄이 이긴다)Sound table. (for the same id, the later row wins)
반환ReturnsSoundSystem 새 소리 체계. (아무것도 받지 않았고 버스도 없다, 크기는 모두 1)A new sound system. (nothing loaded and no buses, all volumes 1)
짝Counterpart: vanilla.js SoundSystem.constructor
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());소리 표의 줄 더하기. (같은 id 는 바꾼다, 받기는 load_sounds 가 한다)
Adds rows to the sound table. (replaces the same id, loading is done by load_sounds)
- sound_tableVec<SoundRow>
- 더할 줄들. (같은 id 의 줄이 있으면 바꾼다)Rows to add. (replaces a row with the same id)
짝Counterpart: vanilla.js SoundSystem.addSounds
pub fn set_external_mute_provider(&mut self, external_mute_provider: Option<Rc<dyn Fn() -> bool>>)#바깥의 음소거를 읽는 함수 설정. (플랫폼 SDK 의 음소거, 보상형 광고를 보이는 동안 등, 매 프레임과 페이지 이벤트 때 읽는다, None 이면 없음)
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_providerOption<Rc<dyn Fn() -> bool>>
- 음소거여야 하면 true 를 돌려주는 함수. (None 이면 바깥 음소거를 보지 않는다)Function that returns true if it should be muted. (None ignores the external mute)
짝Counterpart: vanilla.js SoundSystem.setExternalMuteProvider
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());바깥의 음소거를 읽는 함수 반환.
Returns the function that reads external mute.
반환ReturnsOption<Rc<dyn Fn() -> bool>> 설정한 함수. (없으면 None)The set function. (None if none)
짝Counterpart: vanilla.js SoundSystem.getExternalMuteProvider
pub fn set_autoplay_allowed_provider(&mut self, autoplay_allowed_provider: Option<Rc<dyn Fn() -> bool>>)#누르기 전에 깨워 봐도 되는지 읽는 함수 설정. (웹뷰가 막는 플랫폼이면 false 를 돌려주는 함수, None 이면 허락, 첫 update 에서 한 번 읽는다)
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_providerOption<Rc<dyn Fn() -> bool>>
- 깨워 봐도 되면 true 를 돌려주는 함수. (None 이면 허락)Function that returns true if waking may be tried. (None means allowed)
짝Counterpart: vanilla.js SoundSystem.setAutoplayAllowedProvider
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());누르기 전에 깨워 봐도 되는지 읽는 함수 반환.
Returns the function that reads whether waking before a press is allowed.
반환ReturnsOption<Rc<dyn Fn() -> bool>> 설정한 함수. (없으면 None, 허락으로 친다)The set function. (None if none, treated as allowed)
짝Counterpart: vanilla.js SoundSystem.getAutoplayAllowedProvider
엔진의 AudioManager. (나눠 든 손잡이)
The engine's AudioManager. (a shared handle)
반환Returns&AudioManager 엔진과 같은 AudioContext 를 보는 AudioManager.AudioManager that sees the same AudioContext as the engine.
짝Counterpart: vanilla.js SoundSystem.getAudioManager
배경음악과 효과음의 버스. (원본 getMusicBus, getEffectBus, 첫 누름 전에는 None)
Background music and sound effect buses. (the original getMusicBus, getEffectBus, None before the first press)
반환ReturnsOption<&AudioBus> 배경음악 버스. (첫 누름 뒤의 update 전이거나 AudioContext 를 만들지 못했으면 None)Background music bus. (None before the update after the first press or if the AudioContext could not be created)
짝Counterpart: vanilla.js SoundSystem.getMusicBus
효과음 버스. (원본 getEffectBus, 첫 누름 전에는 None)
Sound effect bus. (the original getEffectBus, None before the first press)
반환ReturnsOption<&AudioBus> 효과음 버스. (첫 누름 뒤의 update 전이거나 AudioContext 를 만들지 못했으면 None)Sound effect bus. (None before the update after the first press or if the AudioContext could not be created)
짝Counterpart: vanilla.js SoundSystem.getEffectBus
틀어 달라고 한 배경음악. (없으면 "")
Background music requested to play. ("" if none)
반환Returns&str 틀어 달라고 한 배경음악 id. (없으면 "")Requested background music id. ("" if none)
짝Counterpart: vanilla.js SoundSystem.getMusicId
설정의 음악 크기.
Music volume setting.
반환Returnsf64 설정의 음악 크기. (0 ~ 1, 처음은 1)Music volume setting. (0 ~ 1, initially 1)
짝Counterpart: vanilla.js SoundSystem.getMusicVolume
음악의 비. (멈춤 창의 반 크기 등)
Music ratio. (half volume for the pause window, etc.)
반환Returnsf64 음악의 비. (0 ~ 1, 처음은 1)Music ratio. (0 ~ 1, initially 1)
짝Counterpart: vanilla.js SoundSystem.getMusicScale
설정의 효과음 크기.
Sound effect volume setting.
반환Returnsf64 설정의 효과음 크기. (0 ~ 1, 처음은 1)Sound effect volume setting. (0 ~ 1, initially 1)
짝Counterpart: vanilla.js SoundSystem.getSoundEffectVolume
사용자의 음소거 단추를 눌러 두었는지.
Whether the user's mute button is pressed.
반환Returnsbool 사용자 음소거를 걸어 두었으면 true.True if user mute is set.
짝Counterpart: vanilla.js SoundSystem.isUserMuted
창이 포커스를 잃으면 음소거하는지. (터치가 주된 기기)
Whether to mute when the window loses focus. (touch-primary devices)
반환Returnsbool 터치가 주된 기기라 포커스를 잃으면 음소거하면 true. (만들 때 정한다)True if it is a touch-primary device that mutes on losing focus. (decided at creation)
짝Counterpart: vanilla.js SoundSystem.isBlurMuteEnabled
창이 포커스를 잃었는지. (음소거하는 기기에서만 true)
Whether the window has lost focus. (true only on devices that mute)
반환Returnsbool 포커스를 잃어 음소거 중이면 true.True if muted from losing focus.
짝Counterpart: vanilla.js SoundSystem.isWindowBlurred
음소거로 AudioContext 를 멈춰 두었는지.
Whether the AudioContext has been stopped due to mute.
반환Returnsbool 음소거로 AudioContext 를 멈춰 두었으면 true.True if the AudioContext was suspended by mute.
짝Counterpart: vanilla.js SoundSystem.isContextPaused
마지막으로 다시 깨워 본 때. (초, 아직 없으면 -무한대)
Last time waking was retried. (seconds, negative infinity if not yet)
반환Returnsf64 마지막으로 다시 깨워 본 때. (SoundSystem 을 만든 때부터 센 벽시계 초, 아직 없으면 f64::NEG_INFINITY)Last time waking was retried. (wall clock seconds since the SoundSystem was created, f64::NEG_INFINITY if not yet)
짝Counterpart: vanilla.js SoundSystem.getLastContextResumeTime
지금 음소거여야 하는지. (플랫폼의 음소거, 사용자의 음소거 단추, 페이지가 가려짐, 창이 포커스를 잃음, 설정한 크기보다 먼저이다)
Whether it should be muted now. (platform mute, the user's mute button, page hidden, window lost focus, takes precedence over the volume setting)
반환Returnsbool 하나라도 맞아 음소거여야 하면 true.True if any condition holds and it should be muted.
짝Counterpart: vanilla.js SoundSystem.readMuted
AudioContext 가 돌고 있는지. (돌지 않으면 소리를 내지 않는다)
Whether the AudioContext is running. (no sound plays if it is not)
반환Returnsbool AudioContext 가 있고 돌고 있으면 true.True if there is an AudioContext and it is running.
짝Counterpart: vanilla.js SoundSystem.isContextRunning
소리 받기. (효과음을 먼저, 배경음악을 나중에, 못 받은 소리는 건너뛴다, 이미 받은 것은 다시 받지 않는다, 애셋 폴더 기준 경로)
- 끝에 update 를 한 번 부른다. (데스크탑은 이때 소리 장치를 연다)
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.
반환ReturnsSoundLoadHandle 걸어 둔 모든 소리 애셋(앞서 받은 것까지)을 기다리는 손잡이. (await 하면 다 받거나 실패할 때까지 기다린다)Handle that waits for all requested sound assets (including previously loaded ones). (awaiting it waits until all are loaded or fail)
짝Counterpart: vanilla.js SoundSystem.loadSounds
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");받기를 건 소리가 다 끝나기를 기다리는 퓨처. (원본 await loadSounds() 의 await 자리, load_sounds 뒤에 엔진 작업 안에서 await 한다)
- 부를 때 든 소리 애셋을 나눠 들어 소리 체계를 빌리지 않는다. 못 받은 소리는 건너뛴다. (원본처럼 거부되지 않는다)
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)
반환ReturnsSoundLoadFuture 부를 때 걸려 있는 소리 애셋을 다 받거나 실패하면 끝나는 퓨처. (걸린 것이 없으면 바로 끝난다)Future that finishes when the sound assets requested at call time have all loaded or failed. (finishes immediately if none are requested)
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());소리 하나 받기. (무리면 모두, 못 받은 것은 None 으로 두고 알린 뒤 건너뛴다)
- 소리 표에는 더하지 않는다. (play_effect, play_music 은 표에 있는 id 만 낸다) 같은 id 로 받아 둔 것은 바꾼다.
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
- 받을 소리 줄. (paths 를 모두 받는다)Sound row to load. (loads all of paths)
짝Counterpart: vanilla.js SoundSystem.loadSound
소리 애셋 직접 더하기. (메모리에서 지은 소리처럼 파일로 받지 않는 것, 같은 id 의 녹음 무리에 덧붙인다)
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
- 덧붙일 소리 id. (소리 표에 그 id 의 줄이 있어야 난다)Sound id to append to. (plays only if the sound table has a row for that id)
- audio_assetRc<AudioAsset>
- 더할 소리 애셋. (읽힌 것만 고른다)Sound asset to add. (only loaded ones are picked)
짝Counterpart: vanilla.js SoundSystem.addSoundAsset
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);설정의 음악 크기. (0 ~ 1)
Music volume setting. (0 ~ 1)
- music_volumef64
- 음악 크기. (0 ~ 1 로 자르고, 유한한 수가 아니면 0)Music volume. (clamped to 0 ~ 1, 0 if not a finite number)
짝Counterpart: vanilla.js SoundSystem.setMusicVolume
음악의 비. (0 ~ 1, 멈춤 창이 떠 있는 동안 반 크기처럼 설정과 따로 줄일 때)
Music ratio. (0 ~ 1, to lower it separately from the setting, such as half volume while the pause window is up)
- music_scalef64
- 음악 크기에 곱할 비. (0 ~ 1 로 자르고, 유한한 수가 아니면 0)Ratio to multiply the music volume by. (clamped to 0 ~ 1, 0 if not a finite number)
짝Counterpart: vanilla.js SoundSystem.setMusicScale
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);설정의 효과음 크기. (0 ~ 1)
Sound effect volume setting. (0 ~ 1)
- sound_effect_volumef64
- 효과음 크기. (0 ~ 1 로 자르고, 유한한 수가 아니면 0)Sound effect volume. (clamped to 0 ~ 1, 0 if not a finite number)
짝Counterpart: vanilla.js SoundSystem.setSoundEffectVolume
사용자의 음소거 단추. (음악과 효과음을 한꺼번에)
The user's mute button. (music and sound effects at once)
- is_user_mutedbool
- true 면 음소거, false 면 풀기. (다른 음소거가 남아 있으면 그대로 음소거)true mutes, false unmutes. (stays muted if another mute remains)
짝Counterpart: vanilla.js SoundSystem.setUserMuted
배경음악 틀기. (반복한다, "" 이면 끈다, 받기 전이거나 첫 누름 전이면 그때 튼다)
- fade_seconds 동안 앞 음악은 줄고 새 음악은 0 에서 오른다. (0 이면 바로)
- is_resumed 면 그 음악을 멈췄던 자리에서 잇는다. (아니면 처음부터)
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
- 틀 배경음악 id. ("" 이면 끈다, 지금 틀어 달라고 한 것과 같으면 아무것도 하지 않는다)Background music id to play. ("" turns it off, does nothing if it is the same as the one currently requested)
- fade_secondsf64
- 겹쳐 바꾸는 시간. (초, 0 이면 바로, 음수는 0)Crossfade time. (seconds, 0 switches immediately, negative is treated as 0)
- is_resumedbool
- true 면 그 음악을 멈췄던 자리에서 잇는다. (멈춘 자리는 소리마다 기억한다)true resumes that music from where it stopped. (the stop position is remembered per sound)
짝Counterpart: vanilla.js SoundSystem.playMusic
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);
}효과음 내기. (음소거, 첫 누름 전, 받기 전, 다시 낼 간격 안이면 내지 않는다)
- volume: 이번의 크기. (0 ~ 1, 소리의 크기와 설정의 효과음 크기에 곱한다) pan: 좌우. (-1 왼쪽 ~ 1 오른쪽, 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
- 낼 효과음 id. (소리 표에 있고 받아 둔 것)Sound effect id to play. (one in the sound table and already loaded)
- volumef64
- 이번의 크기. (0 ~ 1, 소리의 크기와 곱해 0 ~ 1 로 자르고 0.001 이하면 내지 않는다)Volume for this play. (0 ~ 1, multiplied by the sound's volume and clamped to 0 ~ 1, not played if 0.001 or less)
- panf64
- 좌우. (-1 왼쪽 ~ 1 오른쪽, 0 가운데, 범위 밖은 자르고 유한한 수가 아니면 0)Pan. (-1 left ~ 1 right, 0 center, out of range is clamped, 0 if not a finite number)
짝Counterpart: vanilla.js SoundSystem.playEffect
use vanilla::SoundSystem;
fn play_hit(sound_system: &mut SoundSystem) {
sound_system.play_effect("hit", 0.5, -0.8);
}나는 효과음을 줄여 끄기. (sound_id 가 "" 이면 모든 효과음, 줄이는 초가 0 이면 바로 끊음)
- 원본처럼 지금 크기에서 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
- 줄여 끌 효과음 id. ("" 이면 모든 효과음)Sound effect id to fade out. ("" for all sound effects)
- fade_secondsf64
- 줄이는 시간. (초, 0 이하이거나 AudioContext 가 없으면 바로 끊는다)Fade out time. (seconds, stops immediately if 0 or less or if there is no AudioContext)
짝Counterpart: vanilla.js SoundSystem.fadeOutEffects
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);
}나는 효과음을 모두 끊기. (멈춤 창이 뜰 때 등)
Cuts off all playing sound effects. (when the pause window opens, etc.)
짝Counterpart: vanilla.js SoundSystem.stopEffects
나는 효과음 수. (줄여 끄는 중인 것은 빼고)
Number of playing sound effects. (excluding ones fading out)
반환Returnsusize 나고 있는 효과음 수. (끝난 것은 update 가 목록에서 뺀다)Number of sound effects playing. (update removes finished ones from the list)
짝Counterpart: vanilla.js SoundSystem.getEffectVoiceCount
매 프레임. (첫 누름 뒤 소리의 길 만들기, 플랫폼의 음소거 따르기, 배경음악 틀기, 크기 걸기)
Every frame. (builds the sound path after the first press, follows the platform mute, plays background music, applies volumes)
짝Counterpart: vanilla.js SoundSystem.update
함수Functions
함께 쓰는 소리 정하기. (None 이면 비운다)
Sets the shared sound. (None clears it)
- sound_systemOption<Rc<RefCell<SoundSystem>>>
- 함께 쓸 소리 체계. (None 이면 비운다, 스레드마다 따로 든다)Sound system to share. (None clears it, held separately per thread)
짝Counterpart: vanilla.js setSoundSystem
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());함께 쓰는 소리. (아직 없으면 None)
The shared sound. (None if not yet)
반환ReturnsOption<Rc<RefCell<SoundSystem>>> 이 스레드에 set_sound_system 으로 정한 소리 체계. (정하지 않았거나 비웠으면 None)Sound system set on this thread with set_sound_system. (None if not set or cleared)
짝Counterpart: vanilla.js readSoundSystem