Skip to main content
Version: Next

AudioBufferSourceNode

The AudioBufferSourceNode is an AudioScheduledSourceNode which represents an audio source with in-memory audio data, stored in AudioBuffer. You can use it for audio playback, including standard pause and resume functionalities.

An AudioBufferSourceNode can be started only once, so if you want to play the same sound again you have to create a new one. However, this node is very inexpensive to create, and what is crucial you can reuse same AudioBuffer.

Loading...

Constructor

constructor(context: BaseAudioContext, options?: AudioBufferSourceOptions)

AudioBufferSourceOptions

ParameterTypeDefault
buffer
Optional
AudioBuffer-Initial value for buffer.
loop
Optional
booleanfalseInitial value for loop.
loopStart
Optional
number0Initial value for loopStart.
loopEnd
Optional
number0Initial value for loopEnd.
detune
Optional
number0Initial value for detune.
playbackRate
Optional
number1.0Initial value for playbackRate.
pitchCorrection
Optional
booleanfalseEnables the pitch correction algorithm when changing playbackRate.
info

You can also create an AudioBufferSourceNode via BaseAudioContext.createBufferSource(), which uses default values.

info

To use the pitchCorrection option in the web environment, you need to call npx setup-rn-audio-web react-native-audio-api and paste its result into your bundler public directory.

caution

The pitch correction algorithm introduces processing latency. As a result, when scheduling precise playback times, you should start input samples slightly ahead of the intended playback time. Use getLatency() to obtain the compensation value for the current playbackRate.

If you plan to play multiple buffers one after another, consider using AudioBufferQueueSourceNode.

Example

import React, { useEffect, useRef, FC } from 'react';
import {
AudioContext,
AudioBufferSourceNode,
} from 'react-native-audio-api';

function App() {
const audioContextRef = useRef<AudioContext | null>(null);
if (!audioContextRef.current) {
audioContextRef.current = new AudioContext();
}
const audioBufferSource = audioContextRef.current.createBufferSource();
const buffer = ...; // Load your audio buffer here
audioBufferSource.buffer = buffer;
audioBufferSource.connect(audioContextRef.current.destination);
audioBufferSource.start(audioContextRef.current.currentTime);
}

Properties

Inherits all properties from AudioScheduledSourceNode.

AudioNodeproperties
NameTypeDescription
detuneAudioParamk-rate AudioParam representing detuning of oscillation in cents.
playbackRateAudioParamk-rate AudioParam defining speed factor at which the audio will be played.
bufferAudioBufferAssociated AudioBuffer.
loopbooleanBoolean indicating if audio data must be replayed after when end of the associated AudioBuffer is reached.
loopSkipbooleanBoolean indicating if upon setting up loopStart we want to skip immediately to the loop start.
loopStartnumberFloat value indicating the time, in seconds, at which playback of the audio must begin, if loop is true.
loopEndnumberFloat value indicating the time, in seconds, at which playback of the audio must end and loop back to loopStart, if loop is true.

Methods

It inherits all methods from AudioScheduledSourceNode.

getLatency

Returns an estimated scheduling compensation for the WSOLA pitch-correction path, in seconds. Use this value when calling start() — do not hardcode a fixed delay.

ConditionReturned value
pitchCorrection: false0.0
pitchCorrection: true0.01 + 0.02 × playbackRate (seconds)

At playbackRate = 1.0, that is 0.03s. At playbackRate = 1.5, that is 0.04s. Read playbackRate and call getLatency() immediately before scheduling — the estimate scales with the current rate.

Returns 0.0 when pitch correction is disabled.

Returns: number.

Example usage

const source = audioContext.createBufferSource({ pitchCorrection: true });
source.buffer = buffer;
source.connect(audioContext.destination);

const latency = source.getLatency();

// Schedule playback slightly earlier to compensate for latency
const startTime = audioContext.currentTime + 1.0; // play in 1 second
source.start(startTime - latency);

start
Overridden

Schedules the AudioBufferSourceNode to start playback of audio data contained in the associated AudioBuffer, or starts to play immediately.

ParameterTypeDescription
when
Optional
numberThe time, in seconds, at which playback is scheduled to start. If when is less than AudioContext.currentTime or set to 0.0, the node starts playing immediately.
Default: 0.0.
offset
Optional
numberThe position, in seconds, within the audio buffer where playback begins.
The default value is 0.0, which starts playback from the beginning of the buffer. If the offset exceeds the buffer’s duration (or the defined loopEnd value), it’s automatically clamped to the valid range.
Offsets are calculated using the buffer’s natural sample rate rather than the current playback rate — so even if the sound is played at double speed, halfway through a 10-second buffer is still 5 seconds.
duration
Optional
numberThe playback duration, in seconds. If not provided, playback continues until the sound ends naturally or is manually stopped with stop() method.
Equivalent to calling start(when, offset) followed by stop(when + duration).

Errors:

Error typeDescription
RangeErrorwhen is negative number.
RangeErroroffset is negative number.
RangeErrorduration is negative number.
InvalidStateErrorIf node has already been started once.

Returns undefined.

Events

It inherits all events from AudioScheduledSourceNode.

onPositionChanged
Mobile only

Allows to set (or remove) a callback that will be fired after processing certain part of an audio. Frequency is defined by onPositionChangedInterval. By setting this callback you can achieve pause functionality. You can remove the callback by passing null.

onPositionChangedInterval
Mobile only

Allows to set frequency for onPositionChanged event. Value that can be set is around 1000/x Hz.

import { AudioContext, AudioBufferSourceNode } from 'react-native-audio-api';

function App() {
const ctx = new AudioContext();
const sourceNode = ctx.createBufferSource();
sourceNode.buffer = null; //set your buffer
let offset = 0;

sourceNode.onPositionChanged = (event) => { //setting callback
this.offset = event.value;
};

sourceNode.onPositionChangedInterval = 100; //setting frequency to ~10Hz

sourceNode.start();
}

onLoopEnded

Sets (or removes) a callback that will be fired when buffer source node reached the end of the loop and is looping back to loopStart. You can remove the callback either by passing null or calling remove on the returned subscription.

const subscription = audioBufferSourceNode.onLoopEnded = () => { // setting the callback
console.log("loop ended");
};

subscription.remove(); // removal of the subscription

Remarks

detune

  • Default value is 0.0.
  • Nominal range is -∞ to ∞.
  • For example value of 100 detune the source up by one semitone, whereas -1200 down by one octave.

playbackRate

  • Default value is 1.0.
  • Nominal range is -∞ to ∞.
  • For example value of 1.0 plays audio at normal speed, whereas value of 2.0 plays audio twice as fast as normal speed.
  • When created with pitchCorrection it is clamped to range -4 to 4 and uses the WSOLA pitch-correction algorithm when the rate is not 1.0.

buffer

  • If is null, it outputs a single channel of silence (all samples are equal to 0.0).

loop

  • Default value is false.

loopStart

  • Default value is 0.0.

loopEnd

  • Default value is buffer.duration.