Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I stop and resume a live audio stream in HTML5 instead of just pausing it?

A notable issue that's appearing as I'm building a simple audio streaming element in HTML5 is that the <audio> tag doesn't behave as one would expect in regards to playing and pausing a live audio stream.

I'm using the most basic HTML5 code for streaming the audio, an <audio> tag with controls, the source of which is a live stream.

Current outcome: When the stream is first played, it plays whatever is streaming as expected. When it's paused and played again, however, the audio resumes exactly where it left off when the stream was previously paused. The user is now listening to a delayed version of the stream. This occurrence isn't browser-specific.

Desired outcome: When the stream is paused, I want the stream to stop. When it is played again, I want it resume where the stream is currently at, not where it was when the user paused the stream.

Does anyone know of a way to make this audio stream resume properly after it's been paused?

Some failed attempts I've made to fix this issue:

  • Altering the currentTime of the audio element does nothing to streaming audio.
  • I've removed the audio element from the DOM when the user stops stream playback and added it back in when user resumes playback. The stream still continues where the user left off and worse yet downloads another copy of the stream behind the scenes.
  • I've added a random GET variable to the end of the stream URL every time the stream is played in an attempt to fool the browser into believing that it's playing a new stream. Playback still resumes where the user paused the stream.
like image 271
Cole Avatar asked Dec 02 '14 20:12

Cole


People also ask

How do you close audio in HTML?

The pause() method halts (pauses) the currently playing audio. Tip: This method is often used together with the play() method.


1 Answers

Best way to stop a stream, and then start it again seems to be removing the source and then calling load:

var sourceElement = document.querySelector("source");
var originalSourceUrl = sourceElement.getAttribute("src");
var audioElement = document.querySelector("audio");

function pause() {
    sourceElement.setAttribute("src", "");
    audioElement.pause();
    // settimeout, otherwise pause event is not raised normally
    setTimeout(function () { 
        audioElement.load(); // This stops the stream from downloading
    });
}

function play() {
    if (!sourceElement.getAttribute("src")) {
        sourceElement.setAttribute("src", originalSourceUrl);
        audioElement.load(); // This restarts the stream download
    }
    audioElement.play();
}
like image 110
Ciantic Avatar answered Nov 07 '22 03:11

Ciantic