getSoundState
Get a snapshot of everything a player UI needs about one sound: whether it plays, where it is, how long it runs, and its volume and pan. It is cheap enough to call every animation frame.
getSoundState(id: string): SoundStateInfo;
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
id | string | required | ID of the sound, stream or overlapping instance. |
Returns
SoundStateInfo, an object with these fields:
| Field | Type | Description |
|---|---|---|
state | SoundState | 'playing', 'paused' or 'stopped'. |
progress | number | Position in the file as a ratio from 0 to 1, rounded to 4 decimals. |
currentTime | number | Position in the file in seconds, whatever the playback rate. |
elapsedTime | number | Same as currentTime. |
adjustedElapsedTime | number | The time it took to hear that far: elapsedTime divided by the playback rate. |
duration | number | Length of the file in seconds. |
rawDuration | number | null | Length of the file in seconds. |
startTime | number | While playing, the AudioContext time at which the file would have been at 0. For a stream, its startTime option. |
playbackRate | number | null | Current playback rate. |
volume | number | Volume from 0 to 1. |
pan | number | Stereo pan from -1 (left) to 1 (right). |
panSpatialPosition | { x: number; y: number; z: number } | Position in 3D space. |
For an id that is not loaded you get a neutral stopped state: zeros for the times and progress, the configured default volume and playback rate, pan 0 and position 0, 0, 0.
Example
import { SoundHub } from 'soundhub';
const soundHub = new SoundHub();
await soundHub.loadSound('music', '/audio/theme.mp3');
soundHub.play('music', { loop: true });
function render() {
const { state, currentTime, duration, progress } = soundHub.getSoundState('music');
label.textContent = `${state}: ${currentTime.toFixed(1)} / ${duration.toFixed(1)}s`;
seekBar.value = progress;
requestAnimationFrame(render);
}
render();
Try it
Ask a sound where it is
IdleisPlaying()false
isPaused()false
isStopped()true
Exactly one of the three is true at any moment. The values are read five times a second.
Code
Your clicks show up here as soundhub calls
Good to know
- A looping sound reports its position inside the file, so
currentTimeandprogresswrap back to 0 on every loop. - Every time is in the file's own seconds, for buffered sounds and streams alike. Before 6.4.0 a buffered sound divided
currentTime,elapsedTimeanddurationby the playback rate. For a stream,rawDurationisnullwhen the length is not known, as for a live stream. - An unknown id does not throw, but the error is logged, stored for
getLastErrorand dispatched as anerrorevent. - The
progressevent fromstartProgressTrackingcarries this same object asevent.state, so a listener does not have to poll.
See also
getCurrentTime: only the current time.getProgress: only the progress ratio.isPlaying: only the playing check.soundState: theSoundStatevalues.