Continuously streaming random audio from database

后端 未结 1 361
野趣味
野趣味 2021-01-27 00:45

I\'m planning out a project for a very simple audio streamer that would take a mysql database list of songs hosted on my local server, and then randomly stream a song from the l

相关标签:
1条回答
  • 2021-01-27 01:41

    HTML5 audio tag has an event "onended" which is run when the media reaches its end, but since you wish to keep playing you should use the "onwaiting" event, which also fires when the media reaches its end, but keeps itself ready to accept a new track/data.

    You can then use the XMLHttpRequest object to query for the next track to play, eg.

    <script type="text/javascript">
      function getNextTrack(e) {
        var xhttp = new XMLHttpRequest();
        xhttp.open("GET", "next_track.php", false);
        xhttp.send("");
    
        var playback = xhttp.responseXML.childNodes[0];
        for(i = 0; i < playback.childNodes.length; ++i) {
          if (playback.childNodes[i].nodeName != 'track') continue;
          var value = playback.childNodes[i].childNodes[0].nodeValue;
          e.currentTarget.src = value;
          break;
        }
      }
    </script>
    <audio id="player" onwaiting="javascript: getNextTrack(e)" src="first_track.ogg"></audio>
    

    The xml would be in the form of:

    <?xml version="1.0" encoding="UTF-8" ?> 
    <playback> 
        <track>next_song.ogg</track>
    </playback>
    
    0 讨论(0)
提交回复
热议问题