getDuration
Get how long a sound is, in seconds. Use it for a total-time label or to size a seek bar.
getDuration(id: string): number;
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
id | string | required | ID of the sound, stream, sprite sound or overlapping instance. |
Returns
number: the length of the audio in seconds. 0 for an id that is not loaded, and for a stream whose length is not known.
Example
import { SoundHub } from 'soundhub';
const soundHub = new SoundHub();
await soundHub.loadSound('music', '/audio/theme.mp3');
const duration = soundHub.getDuration('music');
totalLabel.textContent = `${Math.floor(duration / 60)}:${String(Math.floor(duration % 60)).padStart(2, '0')}`;
Try it
Read the playback position
IdlegetCurrentTime()0.0 s
getDuration()0.0 s
getProgress()0.000
getProgressPercentage()0%
0:00 of 0:00. getProgress is a ratio from 0 to 1, getProgressPercentage the same value from 0 to 100.
Code
Your clicks show up here as soundhub calls
Good to know
- This is the length of the file. It does not change with the playback rate, and the
durationplay option does not shorten it.getCurrentTimeandseekuse the same scale. - A sprite sound such as
ui_jumpreports the length of its range. - A live stream, or a stream whose metadata has not arrived, reports
0instead ofInfinityorNaN. - For an id that is not loaded, the error is logged, stored for
getLastErrorand dispatched as anerrorevent.
See also
getCurrentTime: where playback is now.getProgress: the position as a ratio.getSoundState: time, duration and state in one object.