Search code examples
javascripthtmlhtml5-audio

How to load a file into a html5 audio tag


How would a I load a audio file from a <input type="file"> tag into a audio tag? I have tried :

<input type="file" id="file"></input>
<script>
var file = document.getElementById("file");
var audio = document.createElement("audio");
audio.src = file.value;
document.write(audio)
</script>

Solution

  • I believe it will satisfy your needs. First, the file input needs to be bound via JavaScript or jQuery (if you prefer). You can use Blob browser support

    The following is a very basic example;

    <input type="file" id="file"></input>
    <audio id="audio" controls autoplay></audio>
    

    We bind the #file for changes using AddEventListener as below

    // Check for BlobURL support
    var blob = window.URL || window.webkitURL;
        if (!blob) {
            console.log('Your browser does not support Blob URLs :(');
            return;           
        }
    
    document.getElementById('file').addEventListener('change', function(event){
    
            consolePrint('change on input#file triggered');
            var file = this.files[0],
             fileURL = blob.createObjectURL(file);
            console.log(file);
            console.log('File name: '+file.name);
            console.log('File type: '+file.type);
            console.log('File BlobURL: '+ fileURL);
            document.getElementById('audio').src = fileURL;
    
    });
    

    Or the other hand, here's a nice and more interactive example I created

    <iframe style="height:600px;width:102.7%;margin:-10px;overflow:hidden;" src="//jsfiddle.net/adamazad/0oy5moph/embedded/result,js,html,css/" allowfullscreen="allowfullscreen" frameborder="0"></iframe>