Search code examples
javascripthtmlhtml5-audiointernet-radio

Use autoplay to play a radio station using HTML5 audio


I'm trying to launch automatically a webradio on my html's file. Currently using autoplay fails, I assume the radio miss the time to load some data hence the autoplay just block. I have created a setTimeout function to handle that. Now the function refuses to launch on Firefox and Opera. The error log of Firefox is far most informative, here reproduced:

NotAllowedError: The play method is not allowed by the user agent or the platform in the current context, possibly because the user denied permission

here my html's snippet:

<body>
  <audio controls src="http://5.63.151.52:7136/stream?icy=http" autoplay id="myAudio">
                Your browser does not support the
                <code>audio</code> element.
        </audio>

  <button onclick={goPlay()}>
            Play
        </button>

  <script>
    // function goPlay(){
    //     console.log("in goplay")
    setTimeout(() => {
        var x = document.getElementById("myAudio");
        // function playAudio() {
        x.play();
      },
      1000
    )
    // }
  </script>
</body>

How handle this situation?

Any hint would be great, thanks


Solution

  • The Firefox error is telling you exactly what's happening. The autoplay isn't working because the user (or more specifically, the browser - see here) is blocking it.

    Any playback that happens before the user has interacted with a page via a mouse click, printable key press, or touch event, is deemed to be autoplay and will be blocked if it is potentially audible.