Search code examples
audiostreaminghtml5-audiohttp-live-streamingicecast

How do I get an <audio> tag to close its connection to stream?


I am making a web-player for my Icecast2 radio, and what I've noticed is that whenever I pause the playback, the browser doesn't close its connection to the Icecast stream unless the server forcibly closes it (in case of Icecast, that happens if the client falls too far behind on its data queue). That behaviour is really sub-optimal, as it forces the client to fall behind the radio stream and forces the server to do the work it shouldn't have to do, not to mention the listener count being inaccurate.

I did explore my options a little bit. I tried calling .load() on the tag, that reopens the connection. It does kill the old one, but that doesn't achieve the state of there being no active connection. I inadvertently tried destroying the audio tag and making a new one, but that doesn't close any connections (is that a bug?).

I did not yet try switching between multiple sources. If that does the trick, I'll write my own answer unless anyone beats me to it. Otherwise, I am open to your suggestions.


Solution

  • You can do this by removing the src attribute.

    const audio = document.querySelector('audio');
    audio.removeAttribute('src');
    audio.load();
    

    See also: https://html.spec.whatwg.org/multipage/media.html#best-practices-for-authors-using-media-elements

    I inadvertently tried destroying the audio tag and making a new one, but that doesn't close any connections (is that a bug?).

    You should show a code example for how you're destroying that audio element. I suspect there is a bug in your code. There used to be a lot of browser bugs around this sort of thing, but that was many years ago. I suspect those issues have long since been resolved.