Decoding
You can decode audio data independently, without creating an AudioContext, using the exported functions decodeAudioData and
decodePCMInBase64.
If you already have an audio context, you can decode audio data directly using its decodeAudioData function;
the decoded audio will then be automatically resampled to match the context's sampleRate.
Supported file formats:
- aac
- flac
- m4a
- mp3
- mp4
- ogg
- opus
- wav
decodeAudioData
Decodes audio data from either a file path or an ArrayBuffer. The optional sampleRate parameter lets you resample the decoded audio;
if not provided, the original sample rate from the file is used.
| Parameter | Type | Description |
|---|---|---|
input | ArrayBuffer | ArrayBuffer with audio data. |
string | Path to audio file located on the device. | |
sampleRateOptional | number | Target sample rate for the decoded audio. |
Returns Promise<AudioBuffer>.
Example decoding with memory block
const url = ... // url to an audio
const buffer = await fetch(url)
.then((response) => response.arrayBuffer())
// resample decoded audio to 48000 Hz
.then((arrayBuffer) => decodeAudioData(arrayBuffer, 48000))
.catch((error) => {
console.error('Error decoding audio data source:', error);
return null;
});
Example using expo-asset library
import { Asset } from 'expo-asset';
const buffer = await Asset.fromModule(require('@/assets/music/example.mp3'))
.downloadAsync()
.then((asset) => {
if (!asset.localUri) {
throw new Error('Failed to load audio asset');
}
// sampleRate not provided, so file will be decoded in original sampleRate
return decodeAudioData(asset.localUri);
})
decodePCMInBase64
Decodes base64-encoded PCM audio data.
| Parameter | Type | Description |
|---|---|---|
base64String | string | Base64-encoded PCM audio data. |
inputSampleRate | number | Sample rate of the input PCM data. |
inputChannelCount | number | Number of channels in the input PCM data. |
isInterleaved Optional | boolean | Whether the PCM data is interleaved. Default is true. |
Returns Promise<AudioBuffer>
Example decoding with data in base64 format
const data = ... // data encoded in base64 string
// data is interleaved (Channel1, Channel2, Channel1, Channel2, ...)
const buffer = await decodeAudioData(data, 4800, 2, true);