AudioBufferSourceNode: playbackRate property
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
TheplaybackRate property oftheAudioBufferSourceNode interface Is ak-rateAudioParam thatdefines the speed at which the audio asset will be played.
A value of 1.0 indicates it should play at the same speed as its sampling rate,values less than 1.0 cause the sound to play more slowly, while values greater than1.0 result in audio playing faster than normal. The default value is1.0.When set to another value, theAudioBufferSourceNode resamples the audiobefore sending it to the output.
In this article
Value
AnAudioParam whosevalue is afloating-point value indicating the playback rate of the audio as a decimal proportionof the original sampling rate.
Consider a sound buffer containing audio sampled at 44.1 kHz (44,100 samples persecond). Let's see what a few values ofplaybackRate do:
- A
playbackRateof 1.0 plays the audio at full speed, or 44,100 Hz. - A
playbackRateof 0.5 plays the audio at half speed, or 22,050 Hz. - A
playbackRateof 2.0 doubles the audio's playback rate to 88,200 Hz.
Examples
>SettingplaybackRate
In this example, when the user presses "Play", we load an audio track, decode it, and put it into anAudioBufferSourceNode.
The example then sets theloop property totrue, so the track loops, and plays the track.
The user can set theplaybackRate property using arange control.
Note:You canrun the full example live (orview the source.)
let audioCtx;let buffer;let source;const play = document.getElementById("play");const stop = document.getElementById("stop");const playbackControl = document.getElementById("playback-rate-control");const playbackValue = document.getElementById("playback-rate-value");async function loadAudio() { try { // Load an audio file const response = await fetch("rnb-lofi-melody-loop.wav"); // Decode it buffer = await audioCtx.decodeAudioData(await response.arrayBuffer()); } catch (err) { console.error(`Unable to fetch the audio file. Error: ${err.message}`); }}play.addEventListener("click", async () => { if (!audioCtx) { audioCtx = new AudioContext(); await loadAudio(); } source = audioCtx.createBufferSource(); source.buffer = buffer; source.connect(audioCtx.destination); source.loop = true; source.playbackRate.value = playbackControl.value; source.start(); play.disabled = true; stop.disabled = false; playbackControl.disabled = false;});stop.addEventListener("click", () => { source.stop(); play.disabled = false; stop.disabled = true; playbackControl.disabled = true;});playbackControl.oninput = () => { source.playbackRate.value = playbackControl.value; playbackValue.textContent = playbackControl.value;};Specifications
| Specification |
|---|
| Web Audio API> # dom-audiobuffersourcenode-playbackrate> |