resource/audioasset
오디오 애셋.
- 원본 resource/audioasset.js. 소리 파일을 디코딩한 오디오 버퍼를 들고 있다.
- 오디오 버퍼 자리는 백엔드가 채운다. (platform/audio 의 AudioBuffer) 데스크탑: 푼 소리를 Arc 로 든 AudioBuffer. (platform/audio/decode 가 원본의 크롬 decodeAudioData 와 같은 길이, 표본율(44100), 표본으로 푼다. webm, ogg 의 Opus 와 Vorbis, mp3, wav, flac, m4a 와 aac 의 AAC. 꼴은 확장자가 아니라 내용으로 가린다) 웹: 원본과 같은 WebAudio AudioBuffer. (OfflineAudioContext 로 디코딩한다, 없으면 잠시 쓰는 AudioContext)
- 읽기: 데스크탑은 load / load_from_bytes 가 그 자리에서 파일을 읽고 디코딩한 뒤 돌아온다. 실패하면 Err. 웹은 막을 수 없어서 load 가 fetch 와 디코딩을 걸어 두고 바로 Ok 로 돌아온다. 끝나면 is_loaded() 가 참이 되고, 실패하면 get_load_error() 에 까닭이 남는다. 그 전에 플레이어에 실어 둬도 되고, 버퍼가 없는 동안 play 는 아무것도 하지 않는다. load, load_from_bytes, load_from_asset 은 원본처럼 await 할 수 있는 AudioLoadHandle 을 돌려준다. 디코딩까지 끝나면 Ok, 실패하면 까닭(원본 reject)이다. (그 자리에서 실패를 알 수 있는 데스크탑은 손잡이의 get_load_error 로 바로 본다) 이미 읽기를 건 애셋은 wait_for_load().await 로도 기다린다. 엔진에서는 engine.load_audio_asset("sounds/hit.ogg") 로 애셋 폴더 기준 경로를 읽는다.
- 읽기 방식: set_load_type(AudioLoadType). 원본처럼 기본은 통째로 풀기(DecompressOnLoad), 엔진 SoundSystem 의 배경음악만 소리 표에 load_type 이 없으면 스트리밍이다. 스트리밍(Streaming)은 풀지 않고 압축된 자리만 들어, 틀 때 조금씩 푼다. 데스크탑은 풀개 스레드가 조각마다 풀어 링 버퍼로 믹서에 내보내고 (platform/audio/streaming.rs, 통째로 푼 버퍼와 같은 표본), 웹은 원본처럼 HTMLAudioElement 를 MediaElementAudioSourceNode 로 플레이어의 GainNode 에 잇는다. 자동(Automatic)은 AUTOMATIC_STREAMING_BYTE_THRESHOLD(1 MiB)보다 큰 파일만 스트리밍한다.
- 원본과 다른 점: Asset 기반 클래스(애셋 타입)가 없다. 읽기 실패는 예외 대신 Err 로 알린다. (까닭은 원본 getLoadError 처럼 get_load_error() 에 남는다) 플레이어들이 같이 들 수 있게
Rc<AudioAsset>로 쓰고, 웹에서 디코딩이 끝난 뒤 채우도록 안쪽을 RefCell 로 둔다.
Audio asset.
- The original resource/audioasset.js. Holds the audio buffer decoded from a sound file.
- The audio buffer is filled by the backend. (AudioBuffer of platform/audio) Desktop: an AudioBuffer holding the decoded sound in an Arc. (platform/audio/decode decodes it to the same length, sample rate (44100) and samples as the original Chrome decodeAudioData. Opus and Vorbis in webm, ogg, mp3, wav, flac, AAC in m4a and aac. The format is told by content, not extension) Web: the same WebAudio AudioBuffer as the original. (decoded with OfflineAudioContext, or a temporary AudioContext if missing)
- Reading: On desktop load / load_from_bytes read and decode the file on the spot before returning. Err on failure. Web cannot block, so load sets up fetch and decoding and returns Ok right away. When done, is_loaded() becomes true, and on failure the reason stays in get_load_error(). It may be loaded into a player before that, and play does nothing while there is no buffer. load, load_from_bytes, load_from_asset return an AudioLoadHandle that can be awaited as in the original. Ok once decoding finishes, the reason (the original reject) on failure. (desktop, which knows failure on the spot, checks it right away with the handle's get_load_error) An asset whose read has already been started can also be awaited with wait_for_load().await. In the engine, engine.load_audio_asset("sounds/hit.ogg") reads a path relative to the asset folder.
- Load type: set_load_type(AudioLoadType). As in the original the default is full decoding (DecompressOnLoad), and only background music of the engine SoundSystem streams when the sound table has no load_type. Streaming does not decode up front and holds only the compressed source, decoding a little at a time while playing. On desktop a decoder thread decodes chunk by chunk into a ring buffer for the mixer (platform/audio/streaming.rs, the same samples as the fully decoded buffer), and on the web, as in the original, an HTMLAudioElement is connected to the player's GainNode through a MediaElementAudioSourceNode. Automatic streams only files larger than AUTOMATIC_STREAMING_BYTE_THRESHOLD (1 MiB).
- Differences from the original:
There is no Asset base class (asset type). Read failures are reported with Err instead of exceptions. (the reason stays in get_load_error() like the original getLoadError)
It is used as `Rc<AudioAsset>` so players can share it, and its inside is a RefCell so it can be filled after decoding finishes on web.AudioLoadHandlestruct traits Clone, std::fmt::Debug, IntoFuture
오디오 읽기 손잡이. (AudioAsset 의 load 들이 돌려준다. 원본 load 의 Promise 자리, 애셋을 나눠 든다)
Audio load handle. (returned by AudioAsset's load functions. Stands in for the Promise of the original load, shares the asset)
use std::rc::Rc;
use vanilla::AudioAsset;
let audio_asset = Rc::new(AudioAsset::new());
let audio_load_handle = audio_asset.load_from_bytes(vec![0, 1, 2, 3]);
assert!(audio_load_handle.is_finished());
assert!(audio_load_handle.get_load_error().is_some());
assert!(!audio_load_handle.get_audio_asset().is_loaded());읽는 애셋.
The asset being read.
반환Returns&Rc<AudioAsset> 이 손잡이가 나눠 든 오디오 애셋.Audio asset shared by this handle.
읽기 실패의 까닭. (데스크탑은 그 자리에서, 웹은 디코딩이 끝난 뒤 알 수 있다)
Reason the read failed. (known on the spot on desktop, after decoding finishes on web)
반환ReturnsOption<String> 실패 까닭. 읽는 중이거나 읽혔으면 None.Failure reason. None while reading or once read.
끝났는지. (디코딩까지 끝났거나 실패했거나)
Whether it finished. (decoding finished or failed)
반환Returnsbool 디코딩까지 끝났거나 실패했으면 true.true if decoding finished or failed.
AudioLoadFuturestruct traits Clone, Debug, Future
오디오 읽기를 기다리는 퓨처. (AudioLoadHandle 을 await 하거나 wait_for_load 가 돌려준다. 읽기를 걸지 않은 애셋이면 끝나지 않는다)
- 디코딩까지 끝나면 Ok(()), 실패하면 Err(까닭)으로 끝난다.
Future that waits for an audio read. (made by awaiting AudioLoadHandle or returned by wait_for_load. Does not finish for an asset whose read was never started)
- Finishes with Ok(()) once decoding finishes, Err(reason) on failure.
use std::path::Path;
use std::rc::Rc;
use vanilla::{AudioAsset, Engine, EngineConfiguration};
let engine = Engine::new(EngineConfiguration::new());
let audio_asset = Rc::new(AudioAsset::new());
audio_asset.load(Path::new("tests/assets/audio/wav_s16_stereo.wav"));
let audio_load_future = audio_asset.wait_for_load();
let task_handle = engine.spawn_task(|_engine_context| async move {
assert!(audio_load_future.await.is_ok());
});
assert!(task_handle.is_finished());AudioAssetstruct traits Default
오디오 애셋.
- 플레이어들이 같이 들 수 있게
Rc<AudioAsset>로 쓴다. load 들이 Rc 에 대고 부르는 까닭이다.
Audio asset.
- Used as
Rc<AudioAsset>so players can share it. That is why the load functions are called on an Rc.
use std::rc::Rc;
use vanilla::{AudioAsset, Engine, EngineConfiguration};
let engine = Engine::new(EngineConfiguration::new());
let audio_asset = Rc::new(AudioAsset::new());
let audio_load_handle = audio_asset.load_from_asset(&engine, "tests/assets/audio/wav_s16_stereo.wav");
assert!(audio_load_handle.get_load_error().is_none());
assert!(audio_asset.is_loaded());
assert!(audio_asset.get_duration() > 0.0);
assert!(audio_asset.get_audio_buffer().is_some());생성. (비어 있는 애셋, load 로 채운다)
Creates one. (an empty asset, filled with load)
반환ReturnsAudioAsset 버퍼도 실패 까닭도 없는 오디오 애셋.Audio asset with neither a buffer nor a failure reason.
짝Counterpart: vanilla.js AudioAsset.constructor
파일에서 읽기. (데스크탑: 바로 읽고 디코딩한다. 웹: 경로를 주소로 fetch 하고 디코딩을 걸어 둔다, await 할 수 있는 손잡이를 돌려준다)
- 이미 로드된 상태라면 아무것도 하지 않는다.
- 읽기 전에 앞의 실패 까닭을 지운다. 실패하면 까닭이 get_load_error 에 남는다.
Reads from a file. (desktop: reads and decodes right away. Web: fetches the path as a URL and sets up decoding, returns a handle that can be awaited)
- Does nothing if already loaded.
- Clears the previous failure reason before reading. On failure the reason stays in get_load_error.
- asset_path&Path
- 소리 파일 경로. (데스크탑은 파일 경로 그대로, 웹은 fetch 할 주소, 애셋 폴더 기준으로 읽으려면 load_from_asset)Sound file path. (on desktop the file path as is, on the web the URL to fetch, use load_from_asset to load relative to the asset folder)
반환ReturnsAudioLoadHandle 읽기 손잡이. (데스크탑은 그 자리에서 디코딩까지 끝나 있다)Load handle. (on desktop, decoding has already finished on the spot)
짝Counterpart: vanilla.js AudioAsset.load
use std::path::Path;
use std::rc::Rc;
use vanilla::AudioAsset;
let audio_asset = Rc::new(AudioAsset::new());
audio_asset.load(Path::new("tests/assets/audio/wav_u8_mono8k.wav"));
assert!(audio_asset.is_loaded());
assert!((audio_asset.get_duration() - 0.25).abs() < 0.01);
let missing_asset = Rc::new(AudioAsset::new());
let audio_load_handle = missing_asset.load(Path::new("tests/assets/audio/missing.wav"));
assert!(audio_load_handle.get_load_error().is_some());
assert_eq!(missing_asset.get_duration(), 0.0);pub fn load_from_asset(self: &Rc<AudioAsset>, engine: &Engine, relative_path: &str) -> AudioLoadHandle#애셋 경로로 읽기. (데스크탑은 애셋 폴더 후보, 웹은 asset_base_url 기준, "data:" 주소도 된다. 원본 load(경로) 자리, await 할 수 있는 손잡이를 돌려준다)
- 데스크탑의 data: 주소는 형을 보지 않고 바이트를 내용으로 가려 푼다. (원본 decodeAudioData 와 같다, 웹은 브라우저 fetch 가 푼다)
- 데스크탑에서 data: 주소를 풀지 못하면 실패 까닭을 남긴다.
Reads by asset path. (desktop uses the asset folder candidates, web is relative to asset_base_url, "data:" URLs work too. In place of the original load(path), returns a handle that can be awaited)
- On desktop, data: URLs are decoded by telling the bytes apart by content without looking at the type. (same as the original decodeAudioData, on web the browser fetch decodes it)
- On desktop, if a data: URL cannot be decoded, the failure reason is left.
- engine&Engine
- 애셋 폴더 후보와 웹 기준 주소를 가진 엔진.Engine holding the asset folder candidates and web base URL.
- relative_path&str
- 애셋 폴더 기준 상대 경로나 "data:" 주소.Path relative to the asset folder, or a "data:" URL.
반환ReturnsAudioLoadHandle 읽기 손잡이. (데스크탑은 그 자리에서 디코딩까지 끝나 있다)Load handle. (on desktop, decoding has already finished on the spot)
메모리에서 읽기. (파일 내용 그대로. 데스크탑: 바로 디코딩한다. 웹: 디코딩을 걸어 둔다, await 할 수 있는 손잡이를 돌려준다)
- 이미 로드된 상태라면 아무것도 하지 않는다. 꼴은 확장자 없이 내용으로 가린다.
Reads from memory. (the file content as is. Desktop: decodes right away. Web: sets up decoding, returns a handle that can be awaited)
- Does nothing if already loaded. The format is told by content without an extension.
- bytesVec<u8>
- 소리 파일 바이트. (wav, mp3, ogg, webm, flac, m4a, aac)Sound file bytes. (wav, mp3, ogg, webm, flac, m4a, aac)
반환ReturnsAudioLoadHandle 읽기 손잡이. (데스크탑은 그 자리에서 디코딩까지 끝나 있다)Load handle. (on desktop, decoding has already finished on the spot)
짝Counterpart: vanilla.js AudioAsset.loadFromBytes
use std::rc::Rc;
use vanilla::AudioAsset;
let wav_bytes = std::fs::read("tests/assets/audio/wav_s16_stereo.wav").expect("wav file");
let audio_asset = Rc::new(AudioAsset::new());
let audio_load_handle = audio_asset.load_from_bytes(wav_bytes);
assert!(audio_load_handle.is_finished());
assert!(audio_asset.is_loaded());로드 여부.
Whether it is loaded.
반환Returnsbool 디코딩한 버퍼가 들어 있으면 true.true if a decoded buffer is present.
짝Counterpart: vanilla.js Asset.isLoaded
마지막 읽기 실패의 까닭. (웹에서 디코딩이 끝난 뒤에 알 수 있다)
Reason the last read failed. (known on web after decoding finishes)
반환ReturnsOption<String> 실패 까닭. 실패한 적이 없거나 다시 읽기를 걸었으면 None.Failure reason. None if it never failed or a read was started again.
짝Counterpart: vanilla.js AudioAsset.getLoadError
디코딩까지 끝나기를 기다리는 퓨처. (원본 await audioAsset.load() 의 await 자리, 엔진 작업 안에서 await 한다. 실패하면 까닭)
- 애셋을 나눠 들어 빌리지 않는다. 읽기를 걸지 않은 애셋이면 끝나지 않는다.
Future that waits until decoding finishes. (the await of the original await audioAsset.load(), awaited inside an engine task. The reason on failure)
- Shares the asset instead of borrowing it. Does not finish for an asset whose read was never started.
반환ReturnsAudioLoadFuture 디코딩까지 끝나면 Ok(()), 실패하면 Err(까닭)으로 끝나는 퓨처.Future that finishes with Ok(()) once decoding finishes, Err(reason) on failure.
읽기 손잡이. (애셋을 나눠 든다, 읽기를 건 뒤의 것을 모아 기다릴 때)
Load handle. (shares the asset, for gathering and waiting on ones after a read has started)
반환ReturnsAudioLoadHandle 이 애셋을 나눠 든 새 읽기 손잡이.New load handle sharing this asset.
읽기 방식 설정. (다음 load, load_from_bytes 부터, 이미 읽혔으면 바뀌지 않는다)
Sets the load type. (from the next load, load_from_bytes; an asset already loaded does not change)
- load_typeAudioLoadType
- 읽기 방식.Load type.
짝Counterpart: vanilla.js AudioAsset.setLoadType
use std::path::Path;
use std::rc::Rc;
use vanilla::{AudioAsset, AudioLoadType};
let audio_asset = Rc::new(AudioAsset::new());
audio_asset.set_load_type(AudioLoadType::Streaming);
audio_asset.load(Path::new("tests/assets/audio/vorbis_stereo.ogg"));
assert_eq!(audio_asset.get_load_type(), AudioLoadType::Streaming);
assert!(audio_asset.is_streaming());
assert!(audio_asset.get_duration() > 0.0);읽기 방식 반환.
Returns the load type.
반환ReturnsAudioLoadType 읽기 방식. (기본 DecompressOnLoad, 엔진 SoundSystem 의 배경음악만 소리 표에 load_type 이 없으면 Streaming)Load type. (DecompressOnLoad by default, only background music of the engine SoundSystem uses Streaming when the sound table has no load_type)
짝Counterpart: vanilla.js AudioAsset.getLoadType
스트리밍으로 읽혔는지. (읽기 방식이 Automatic 이면 읽은 뒤에 정해진다)
Whether it was loaded for streaming. (with the Automatic load type this is decided after loading)
반환Returnsbool 스트리밍으로 읽혔으면 true. (통째로 풀었거나 읽기 전이면 false)true if loaded for streaming. (false if fully decoded or before loading)
짝Counterpart: vanilla.js AudioAsset.isStreaming
스트리밍 소리의 주소. (원본 getStreamUrl, 웹은 미디어 요소의 src)
Address of the streaming sound. (the original getStreamUrl, the media element src on the web)
반환ReturnsOption<String> 웹은 원본처럼 파일 주소나 blob: 주소, 데스크탑은 파일에서 읽었으면 그 경로. (메모리에서 읽은 데스크탑 스트리밍이나 스트리밍이 아니면 None)On the web the file URL or a blob: URL as in the original, on desktop the path when loaded from a file. (None for desktop streaming loaded from memory or when not streaming)
짝Counterpart: vanilla.js AudioAsset.getStreamUrl
오디오 버퍼 반환. (값싼 복제: 데스크탑은 Arc, 웹은 자바스크립트 객체 참조)
Returns the audio buffer. (cheap clone: Arc on desktop, a JavaScript object reference on web)
반환ReturnsOption<AudioBuffer> 디코딩한 버퍼. 읽히기 전이거나 실패했거나 스트리밍이면 None.Decoded buffer. None before it is read, if it failed, or when streaming.
짝Counterpart: vanilla.js AudioAsset.getAudioBuffer
재생 시간 반환. (초, 읽기 전이면 0)
Returns the duration. (seconds, 0 before loading)
반환Returnsf64 버퍼의 재생 시간. (초) 스트리밍이면 컨테이너가 알리는 길이(원본 미디어 요소의 메타데이터 길이 자리, 데스크탑은 끝까지 한 번 풀고 나면 푼 길이). 읽기 전이면 0.Duration of the buffer. (seconds) When streaming, the length the container reports (in place of the original media element metadata duration; on desktop it becomes the decoded length once decoded to the end). 0 before loading.
짝Counterpart: vanilla.js AudioAsset.getDuration
상수Constants
자동(AudioLoadType::Automatic)일 때 스트리밍으로 고르는 파일 크기. (바이트, 이보다 크면 스트리밍)
- 통째로 풀면 1 초에 채널마다 44100 개의 f32 를 든다. (스테레오 1 초 약 345 KiB, 3 분이면 약 61 MiB) 128 kbps MP3 1 MiB 는 약 65 초라 풀면 약 22 MiB 다. 효과음은 거의 이보다 작고, 이보다 큰 WAV 도 6 초 안팎이라 흘려 틀어도 된다.
File size above which automatic (AudioLoadType::Automatic) picks streaming. (bytes, larger files stream)
- Full decoding holds 44100 f32 values per channel per second. (about 345 KiB per stereo second, about 61 MiB for 3 minutes) 1 MiB of 128 kbps MP3 is about 65 seconds, about 22 MiB when decoded. Sound effects are almost always smaller, and a WAV larger than this is still only around 6 seconds, so streaming it is fine.
반환Returnsu64
짝Counterpart: vanilla.js AUTOMATIC_STREAMING_BYTE_THRESHOLD
use std::path::Path;
use std::rc::Rc;
use vanilla::{AudioAsset, AudioLoadType, AUTOMATIC_STREAMING_BYTE_THRESHOLD};
let path = Path::new("tests/assets/audio/wav_s16_stereo.wav");
assert!(std::fs::metadata(path).unwrap().len() <= AUTOMATIC_STREAMING_BYTE_THRESHOLD);
let audio_asset = Rc::new(AudioAsset::new());
audio_asset.set_load_type(AudioLoadType::Automatic);
audio_asset.load(path);
assert!(!audio_asset.is_streaming());
assert!(audio_asset.get_audio_buffer().is_some());AudioLoadTypeenum traits Clone, Copy, Debug, Default, PartialEq, Eq, Hash
소리 읽기 방식. (원본 AudioLoadType, 유니티 AudioClip 의 Load Type, 언리얼 사운드 웨이브의 스트리밍과 같은 갈래)
Sound load type. (the original AudioLoadType, the same family as Unity AudioClip Load Type and Unreal sound wave streaming)
use std::path::Path;
use std::rc::Rc;
use vanilla::{AudioAsset, AudioLoadType};
let music_asset = Rc::new(AudioAsset::new());
music_asset.set_load_type(AudioLoadType::Streaming);
music_asset.load(Path::new("tests/assets/audio/mp3_stereo.mp3"));
let effect_asset = Rc::new(AudioAsset::new());
effect_asset.set_load_type(AudioLoadType::DecompressOnLoad);
effect_asset.load(Path::new("tests/assets/audio/mp3_stereo.mp3"));
assert!(music_asset.is_streaming());
assert!(music_asset.get_audio_buffer().is_none());
assert!(!effect_asset.is_streaming());
assert!((music_asset.get_duration() - effect_asset.get_duration()).abs() < 0.001);| 이름Name | 설명Description |
|---|---|
Automatic | 크기를 보고 고른다. (AUTOMATIC_STREAMING_BYTE_THRESHOLD 보다 큰 파일은 스트리밍, 아니면 통째로 풀기, 고른 애셋만)Picks by size. (files larger than AUTOMATIC_STREAMING_BYTE_THRESHOLD stream, otherwise full decoding, only for assets that choose it) |
DecompressOnLoad | 읽을 때 PCM 으로 통째로 푼다. (효과음처럼 짧고 자주 겹쳐 트는 소리, 시작이 바로이고 겹쳐 틀어도 싸다, 기본)Fully decodes to PCM on load. (short sounds played often and overlapping, like sound effects; starts immediately and overlapping is cheap, the default) |
Streaming | 풀지 않고 틀 때 조금씩 풀어 흘린다. (배경음처럼 긴 소리, 메모리는 압축된 파일 크기 이하, 데스크탑은 플레이어마다 링 버퍼 128 KiB)Does not decode up front and decodes a little at a time while playing. (long sounds like background music; memory is at most the compressed file size, plus a 128 KiB ring buffer per player on desktop) |