JavaScript Play Uploaded Audio

John White picture John White · Feb 20, 2015 · Viewed 17k times · Source

How do I make it so that when audio is uploaded it can be played? I used this code, but it didn't work.

<input type="file" id="audio" onchange="playFile(this)" />
<audio id="sound"></audio>
<script type="text/javascript">
    function playFile(obj){
        var url=document.getElementById("audio").url;
        document.getElementById("sound").src=url;
        document.getElementById("sound").play()
    }
</script>

Answer

Kaiido picture Kaiido · Feb 20, 2015

[EDIT]

One should not use the FileReader API to load an user selected File into its page.

Instead one should prefer the URL.createObjectURL(File) method.
This will return a blobURI, only accessible from user session, which, in case of user File, is just a direct pointer to the original file, thus taking almost nothing in memory.

input.onchange = function(e){
  var sound = document.getElementById('sound');
  sound.src = URL.createObjectURL(this.files[0]);
  // not really needed in this exact case, but since it is really important in other cases,
  // don't forget to revoke the blobURI when you don't need it
  sound.onend = function(e) {
    URL.revokeObjectURL(this.src);
  }
}
<input type="file" id="input"/>
<audio id="sound" controls></audio>

[Previous answer]

You can't access the full url of a local file with input type="file".

However you can read the file thanks to the file API

input.onchange = function(){
  var sound = document.getElementById('sound');
  var reader = new FileReader();
  reader.onload = function(e) {
    sound.src = this.result;
    sound.controls = true;
    sound.play();
    };
  reader.readAsDataURL(this.files[0]);
}
<input type="file" id="input"/>
<audio id="sound"></audio>