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
| Parameter | Type | Default | Description |
|---|---|---|---|
id | string | required | ID of the sound or stream. |
rate | number | required | Speed 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
Speed up or slow down
IdleThe 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
0or below, orNaN, is ignored without an error. For a buffered sound there is no upper limit in the library. A stream fromloadStreamclamps the rate to0.25to4. - 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
seekedevent 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 onSoundHubInterface. Before 6.4.0, skipping the event also skipped keeping the place, so the sound jumped.
See also
getPlaybackRate: read the current rate.PlayOptions: set the rate when you play.seek: positions are measured at the current rate.