Skip to main content

setPlaybackRate

Change the speed of a sound. 1 is normal speed, 0.5 is half speed and 2 is double. The pitch changes along with the speed.

setPlaybackRate(id: string, rate: number): void;

Parameters​

ParameterTypeDefaultDescription
idstringrequiredID of the sound or stream.
ratenumberrequiredSpeed multiplier. Must be above 0.

Returns​

Nothing.

Example​

import { SoundHub } from 'soundhub';

const soundHub = new SoundHub();
await soundHub.loadSound('music', '/audio/theme.mp3');

soundHub.play('music');

soundHub.setPlaybackRate('music', 0.5); // half speed
soundHub.setPlaybackRate('music', 2); // double speed
soundHub.setPlaybackRate('music', 1); // normal again
tip

To start at a different speed straight away, pass playbackRate to play in the PlayOptions.

Try it​

Try it

Speed up or slow down

Idle
1.00×
0.25×2×

The pitch moves with the speed. That is how the Web Audio API plays a buffer at another rate.

Code
Your clicks show up here as soundhub calls

Good to know​

  • A rate of 0 or below, or NaN, is ignored without an error. For a buffered sound there is no upper limit in the library. A stream from loadStream clamps the rate to 0.25 to 4.
  • The rate is stored in the sound's play options, so the next play() uses it. On a sound that is not playing it is only stored, and no event is dispatched.
  • While the sound plays, it keeps its place in the file. A rate that does not change leaves the sound alone. No seeked event is dispatched; before 6.4.0 one was.
  • Dispatches SoundEventsEnum.PLAYBACK_RATE_CHANGED ('playback_rate_changed'). The class method takes an optional third argument, skipDispatchEvent, to leave the event out. It is not on SoundHubInterface. Before 6.4.0, skipping the event also skipped keeping the place, so the sound jumped.

See also​