Search code examples
javascriptaudioplayback

How do I play the sound of an mp3 file downloaded from the server - I am new to using streamed data


I have a file called test.mp3 on my server - I can play it

I am trying to download it using xmlhttprequest get and then assigning the response to an audio player.

I have tried

servpl.onclick = e =>{
const xhr = new XMLHttpRequest();

xhr.open('GET', 'sounds/test.mp3');

// Send the request over the network
xhr.send();
xhr.onload = function() {
if (xhr.status != 200) { // analyze HTTP status of the response
    alert(`Error ${xhr.status}: ${xhr.statusText}`); // e.g. 404: Not Found
} else { // show the result
    alert(`Done, got ${xhr.response.length} bytes`); // response is the server response
    //    recordedAudio.autoplay=true;
    recordedAudio.src=xhr.response;
    recordedAudio.play();

   document.getElementById("display").innerHTML+=" after play sound";  
 
    }
};
document.getElementById("display").innerHTML+=" Server Play clicked";   

}


Solution

  • You can play that mp3 file using audio tag like so

    <audio autoplay>
      <source src="sounds/test.mp3" type="audio/mpeg">
      Your browser does not support the audio element.
    </audio>
    

    You can also create an audio tag using JS

    var audio = document.createElement('audio');
    audio.src = 'sounds/test.mp3';
    audio.type = 'audio/mpeg';
    document.body.appendChild(audio);
    

    In this case, you will need to monitor readyState to see if the audio is loaded and ready to play. Another option is to add a handler for oncanplay event. Once audio is loaded you can execute audio.play(); to start playing it.

    Note that the major browsers will allow you to execute audio.play() command only from within button.click handler or other event handler triggered by a user. This is a security measure to prevent websites from playing media automatically in the background without allowing users to see/control them.

    Please let me know if this helps.