Search code examples
javascripthtmlaudioclienthtml5-audio

Users uploads audio to play only on client-side javascript


Very simply, I just want a user to choose an audio file from their directory, and have the webpage just play the audio file that they uploaded.

I don't want to send the data to the server; I just want the audio file to reside on clientside.

There's a similar guide to do it for images, but I'm not sure how to get started doing it for audio? What API's am I supposed to use?


Solution

  • Here is a solution using Javascript. I've included comments in the code.

    If you haven't already, just familiarize yourself with the FileReader object and the readAsDataURL method.

    Try uploading an audio file in the snippet below to see it in action.

    //get input by id
    var audioFile = document.getElementById("file")
    //get source by id
    var audioSource = document.getElementById("audioSource");
    //get audio by id
    var audioTag = document.getElementById('audio');
    
    //apply event listener to input using the playAudio function
    audioFile.addEventListener("change", function() {
      playAudio(this);
    });
    
    
    function playAudio(input) {
      //empty var to read file
      var reader;
      //if a file is uploaded then use FileReader to read file
      if (input.files && input.files[0]) {
        reader = new FileReader();
        //onload set the audio source with the uploaded audio
        reader.onload = function(e) {
          audioSource.setAttribute('src', e.target.result);
          //load source
          audioTag.load();
          //play source
          audioTag.play();
        }
        //read contents of of file
        reader.readAsDataURL(input.files[0]);
      }
    }
    <input type="file" id="file">
    <audio id="audio">
      <source id="audioSource" src=""></source>
    </audio>