getStreamElement
Get the HTMLAudioElement behind a stream. soundhub covers playback, volume, panning, rate and progress itself. The element is there for what sits outside that, such as how much of the file has downloaded.
getStreamElement(id: string): HTMLAudioElement | undefined;
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
id | string | required | ID of a sound loaded with loadStream. |
Returns
HTMLAudioElement | undefined: the element, or undefined when the id is not a stream.
Example
A loading bar from the element's buffered ranges:
import { SoundHub } from 'soundhub';
const soundHub = new SoundHub();
await soundHub.loadStream('episode-42', '/audio/episode-42.mp3');
const element = soundHub.getStreamElement('episode-42');
if (element?.buffered.length) {
const loadedUpTo = element.buffered.end(element.buffered.length - 1);
const duration = soundHub.getDuration('episode-42');
bufferBar.style.width = `${(loadedUpTo / duration) * 100}%`;
}
Lock screen controls
If you would rather wire the Media Session yourself than use setMediaSession:
if ('mediaSession' in navigator) {
navigator.mediaSession.metadata = new MediaMetadata({
title: 'Episode 42: naming things',
artist: 'The Podcast',
artwork: [{ src: '/cover-512.png', sizes: '512x512', type: 'image/png' }],
});
navigator.mediaSession.setActionHandler('play', () => soundHub.resume('episode-42'));
navigator.mediaSession.setActionHandler('pause', () => soundHub.pause('episode-42'));
}
Good to know
warning
Do not call play() or pause() or set volume on the element directly. soundhub tracks the state itself and routes volume through a gain node, so going around it puts the two out of step. Use play, pause and setSoundVolume as you would for any other sound.
- The element's own
volumestays at1. The stream's volume lives on its gain node. - Buffered sounds have no element, so this returns
undefinedfor them. - After
unloadSoundthe element has its source cleared and the method returnsundefined.
See also
loadStream: load a long file as a stream.isStream: check whether an id is a stream.setMediaSession: lock screen controls without touching the element.