Skip to main content

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​

ParameterTypeDefaultDescription
idstringrequiredID 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 volume stays at 1. The stream's volume lives on its gain node.
  • Buffered sounds have no element, so this returns undefined for them.
  • After unloadSound the element has its source cleared and the method returns undefined.

See also​