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

后端 未结 3 1168
情书的邮戳
情书的邮戳 2021-01-18 03:42

A notable issue that\'s appearing as I\'m building a simple audio streaming element in HTML5 is that the tag doesn\'t behave as one would expect i

3条回答
  •  情歌与酒
    2021-01-18 04:17

    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();
    }
    

提交回复
热议问题