seek
Jump to a point in a sound. Reach for it to build a seek bar, or to skip an intro.
seek(id: string, time: number, skipDispatchEvent?: boolean): void;
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
id | string | required | ID of the sound or stream. |
time | number | required | Position in seconds. Values below 0 go to the start. |
skipDispatchEvent | boolean | false | When true, no seeked event is dispatched. |
Returns
Nothing.
Example
import { SoundHub } from 'soundhub';
const soundHub = new SoundHub();
await soundHub.loadSound('music', '/audio/theme.mp3');
soundHub.play('music');
// Skip to 15 seconds
soundHub.seek('music', 15);
// Build a progress display
const current = soundHub.getCurrentTime('music');
const duration = soundHub.getDuration('music');
console.log(`${current} / ${duration} seconds`);
Try it
Jump to any point
IdleDrag and let go: seek runs once, on release, with the time in seconds.
Code
Your clicks show up here as soundhub calls
Good to know
- On a playing sound the source restarts at the new point. On a paused or stopped sound only the position is stored, and the next
resume()orplay()starts there. timeis a position in the file, whatever the playback rate:seek('music', 10)lands 10 seconds into the file at any rate.getCurrentTimeandgetDurationuse the same scale. Before 6.4.0 a buffered sound multipliedtimeby the rate.- Seeking to the end or past it does not clamp. A playing looped sound moves on to its next loop, a stopped sound is left alone, and otherwise the sound ends and dispatches
ended. - Dispatches
SoundEventsEnum.SEEKED('seeked') with thecurrentTimewhere the seek landed. - On a stream from
loadStream,timeis seconds in the file, clamped to its duration. For an id that is not loaded, the error is logged, stored forgetLastErrorand dispatched as anerrorevent.
See also
getCurrentTime: read the current position.getDuration: the length of the sound.getProgress: the position as a ratio, for a progress bar.