Play streaming audio in JavaScript

12,444

This code works for us:

<audio id="music" preload="all">
   <source src="http://localhost:8000/a.mp3">
</audio>
<script>
  let music = document.getElementById('music');
  music.play();
</script>
Share:
12,444
Lucas
Author by

Lucas

Updated on June 04, 2022

Comments

  • Lucas
    Lucas about 2 years

    I'm currently using node-lame to encode a raw PCM input stream, and I have the following code in Node.JS that successfully outputs binary MP3 chunks:

    server.on('request', (req, res) => {
      encoded.pipe(res);
    });
    

    I try to request this code inside of my front-end interface with code like the following:

    var audio = new Audio('http://localhost:8000/a.mp3'); // the above
    audio.play();
    

    However, as the audio source is a continuous input stream, the content just keeps getting downloaded without end:

    Endless downloading

    Instead, I want to be able to play the chunks as they are downloaded.

    I can access http://localhost:8000/a.mp3 in an application like VLC or Quicktime Player, and the audio delivery works fine; I'm just stumped as to how to best do this on the web.

    Thanks in advance.