Skip to main content

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.

caution

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.

ParameterTypeDescription
inputArrayBufferArrayBuffer with audio data.
stringPath to audio file located on the device.
sampleRate
Optional
numberTarget 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.

ParameterTypeDescription
base64StringstringBase64-encoded PCM audio data.
inputSampleRatenumberSample rate of the input PCM data.
inputChannelCountnumberNumber of channels in the input PCM data.
isInterleaved
Optional
booleanWhether 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);