vanilladocs
vanillapunch.com
API / resource/audioasset

resource/audioasset

오디오 애셋.

Audio asset.

AudioAssetextends Asset

짝Counterpart: vanilla-engine AudioAsset

오디오 애셋.

Audio asset.

예제Example소리 파일 읽고 길이 보기Load a sound file and check its length
import { AudioAsset } from "./build/vanilla.js";

const audioAsset = new AudioAsset();
await audioAsset.load("examples/assets/beep.wav");
const audioBuffer = audioAsset.getAudioBuffer();
console.log(audioAsset.getDuration(), audioBuffer.sampleRate, audioAsset.getLoadError());
생성자constructorconstructor()#0.0.8 부터since 0.0.8소스source

생성.

Constructor.

짝Counterpart: vanilla-engine AudioAsset.new

메서드methodsetLoadType(loadType)#0.4.0 부터since 0.4.0소스source

읽기 방식 설정. (다음 load, loadFromBytes 부터, 이미 읽혔으면 unload 뒤에 다시 읽어야 바뀐다)

Sets the load type. (from the next load or loadFromBytes, if already loaded it changes only after unload and loading again)

loadTypestring
읽기 방식. (AudioLoadType 의 값, 모르는 값이면 decompressOnLoad)Load type. (a value of AudioLoadType, decompressOnLoad if unknown)

짝Counterpart: vanilla-engine AudioAsset.set_load_type

예제Example긴 배경음을 스트리밍으로 읽기Load long background music as streaming
import { AudioAsset, AudioLoadType } from "./build/vanilla.js";

const audioAsset = new AudioAsset();
audioAsset.setLoadType(AudioLoadType.streaming);
await audioAsset.load("examples/assets/beep.wav");
console.log(audioAsset.getLoadType(), audioAsset.isStreaming(), audioAsset.getDuration());
메서드methodgetLoadType()#0.4.0 부터since 0.4.0소스source

읽기 방식 반환.

Returns the load type.

반환Returnsstring 읽기 방식. (AudioLoadType 의 값, 기본 decompressOnLoad, 엔진 SoundSystem 의 배경음악만 소리 표에 loadType 이 없으면 streaming)Load type. (a value of AudioLoadType, decompressOnLoad by default, only background music of the engine SoundSystem uses streaming when the sound table has no loadType)

짝Counterpart: vanilla-engine AudioAsset.get_load_type

메서드methodisStreaming()#0.4.0 부터since 0.4.0소스source

스트리밍으로 읽혔는지. (읽기 방식이 automatic 이면 읽은 뒤에 정해진다)

Whether it was loaded as streaming. (with the automatic load type this is decided after loading)

반환Returnsboolean 스트리밍으로 읽혔으면 참. (통째로 풀었거나 읽기 전이면 거짓)True if loaded as streaming. (false if fully decompressed or not loaded yet)

짝Counterpart: vanilla-engine AudioAsset.is_streaming

메서드methodgetStreamUrl()#0.4.0 부터since 0.4.0소스source

스트리밍 소리의 주소. (미디어 요소의 src 로 쓴다)

URL of the streaming sound. (used as the media element's src)

반환Returnsstring | null 파일 경로나 blob: 주소. (스트리밍이 아니면 null)A file path or blob: URL. (null if not streaming)

짝Counterpart: vanilla-engine AudioAsset.get_stream_url

메서드methodasync load(assetPath)#0.0.8 부터since 0.0.8소스source

비동기 애셋 로드.

Loads the asset asynchronously.

assetPathstring
소리 파일 경로. (이미 읽혔으면 아무것도 하지 않는다)Sound file path. (does nothing if already loaded)

반환ReturnsPromise<void> 다 읽으면 풀리는 프로미스. (받기나 디코딩이 실패하면 getLoadError 에 까닭을 남기고 거부된다, 디코딩할 수 없는 환경이면 까닭만 남기고 풀린다)A promise resolved when fully loaded. (if fetching or decoding fails it records the reason in getLoadError and rejects, if decoding is not available it only records the reason and resolves)

짝Counterpart: vanilla-engine AudioAsset.load

메서드methodasync loadFromBytes(bytes)#0.4.0 부터since 0.4.0소스source

이미 가진 바이트로 읽기. (내장 자료나 직접 받은 파일, 디코딩이 끝나면 isLoaded() 가 참, 이미 읽혔으면 아무것도 하지 않는다)

Loads from bytes already held. (Built-in data or a directly received file, isLoaded() is true once decoding finishes, does nothing if already loaded)

bytesArrayBuffer | ArrayBufferView
소리 파일의 바이트. (넘긴 것은 바뀌지 않는다)The bytes of the sound file. (What is passed is not changed)

짝Counterpart: vanilla-engine AudioAsset.load_from_bytes

예제Example받아 둔 바이트로 소리 읽기Load a sound from bytes already fetched
import { AudioAsset } from "./build/vanilla.js";

const response = await fetch("examples/assets/beep.wav");
const bytes = await response.arrayBuffer();
const audioAsset = new AudioAsset();
await audioAsset.loadFromBytes(bytes);
console.log(audioAsset.isLoaded(), audioAsset.getDuration(), bytes.byteLength);
메서드methodasync decodeArrayBuffer(arrayBuffer)#0.4.0 부터since 0.4.0소스source

소리 바이트 디코딩. (다 되면 오디오 버퍼를 들고 읽힌 것으로 둔다)

  • 디코딩은 OfflineAudioContext 로 한다. (스피커를 잡지 않고, user gesture 전에 만들어도 자동재생 경고가 없으며, 여러 애셋을 한꺼번에 받아도 실시간 AudioContext 의 개수 제한에 걸리지 않는다) 없으면 잠시 쓰는 AudioContext 로 한다.

Decodes the sound bytes. (When done, holds the audio buffer and marks it as loaded)

  • Decoding is done with OfflineAudioContext. (It does not grab the speaker, creating it before a user gesture gives no autoplay warning, and receiving many assets at once does not hit the real-time AudioContext count limit) If it is unavailable, a temporary AudioContext is used.
arrayBufferArrayBuffer
디코딩이 떼어 가므로 뒤에 다시 쓰지 않는다.Not used again afterward because decoding detaches it.
메서드methodunload()#0.4.0 부터since 0.4.0소스source

애셋 언로드. (오디오 버퍼를 놓고, 이 애셋이 만든 blob: 주소를 놓는다, 읽기 방식은 그대로)

Unloads the asset. (releases the audio buffer and any blob: URL this asset created, the load type stays)

메서드methodgetLoadError()#0.4.0 부터since 0.4.0소스source

마지막 읽기 실패의 까닭. (받기나 디코딩이 실패했으면 글, 아니면 null, 다시 읽기 시작하면 지운다)

The reason for the last load failure. (A string if receiving or decoding failed, otherwise null, cleared when loading starts again)

반환Returnsstring | null 실패 까닭. (없으면 null)Failure reason. (null if none)

짝Counterpart: vanilla-engine AudioAsset.get_load_error

메서드methodgetAudioBuffer()#0.0.10 부터since 0.0.10소스source

오디오 버퍼 반환.

Returns the audio buffer.

반환ReturnsAudioBuffer | null 디코딩한 오디오 버퍼. (읽기 전이거나 스트리밍이면 null)The decoded audio buffer. (null if not loaded yet or streaming)

짝Counterpart: vanilla-engine AudioAsset.get_audio_buffer

메서드methodgetDuration()#0.0.8 부터since 0.0.8소스source

재생 시간 반환.

Returns the playback duration.

반환Returnsnumber 재생 시간. (초, 읽기 전이면 0, 스트리밍이면 메타데이터의 길이)Playback duration. (seconds, 0 if not loaded yet, the metadata duration if streaming)

짝Counterpart: vanilla-engine AudioAsset.get_duration

상수Constants

상수constantAUTOMATIC_STREAMING_BYTE_THRESHOLD#0.4.0 부터since 0.4.0소스source

자동(AudioLoadType.automatic)일 때 스트리밍으로 고르는 파일 크기. (바이트, 이보다 크면 스트리밍)

  • 통째로 풀면 1 초에 채널마다 44100 개의 float32 를 든다. (스테레오 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 float32 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.

짝Counterpart: vanilla-engine AUTOMATIC_STREAMING_BYTE_THRESHOLD

AudioLoadTypeenum

짝Counterpart: vanilla-engine AudioLoadType

소리 읽기 방식. (유니티 AudioClip 의 Load Type, 언리얼 사운드 웨이브의 스트리밍과 같은 갈래)

Sound load type. (the same kind of choice as Unity AudioClip's Load Type and Unreal sound wave streaming)

예제Example배경음은 스트리밍, 효과음은 통째로 풀기Stream background music, fully decompress sound effects
import { AudioAsset, AudioLoadType } from "./build/vanilla.js";

const musicAsset = new AudioAsset();
musicAsset.setLoadType(AudioLoadType.streaming);
await musicAsset.load("examples/assets/beep.wav");
const effectAsset = new AudioAsset();
effectAsset.setLoadType(AudioLoadType.decompressOnLoad);
await effectAsset.load("examples/assets/beep.wav");
console.log(musicAsset.isStreaming(), musicAsset.getAudioBuffer(), effectAsset.isStreaming(), effectAsset.getDuration());
이름Name값Value설명Description
automaticautomatic크기를 보고 고른다. (AUTOMATIC_STREAMING_BYTE_THRESHOLD 보다 큰 파일은 스트리밍, 아니면 통째로 풀기, 고른 애셋만)Chooses by size. (files larger than AUTOMATIC_STREAMING_BYTE_THRESHOLD stream, others are fully decompressed, only for assets that choose it)
decompressOnLoaddecompressOnLoad읽을 때 PCM 으로 통째로 푼다. (효과음처럼 짧고 자주 겹쳐 트는 소리, 시작이 바로이고 겹쳐 틀어도 싸다, 기본)Fully decompresses to PCM on load. (short sounds played often and overlapping, like sound effects, start immediately and are cheap to overlap, the default)
streamingstreaming풀지 않고 미디어 요소(HTMLAudioElement)가 조금씩 풀어 흘린다. (배경음처럼 긴 소리, 메모리는 압축된 파일 크기 이하)Does not decompress, a media element (HTMLAudioElement) decodes and streams it bit by bit. (long sounds like background music, memory is at most the compressed file size)