Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 428
Mason Wright Avatar asked Oct 30 '15 23:10

Mason Wright


People also ask

How do I embed audio in HTML5?

To embed audio in HTML, we use the <audio> tag. Before HTML5, audio cannot be added to web pages in the Internet Explorer era. To play audio, we used web plugins like Flash. After the release of HTML5, it is possible.

How do we insert audio in an HTML file?

HTML Audio - How It WorksThe controls attribute adds audio controls, like play, pause, and volume. The <source> element allows you to specify alternative audio files which the browser may choose from. The browser will use the first recognized format.

How do I add audio to a video in HTML5?

The HTML5 <audio> and <video> tags make it simple to add media to a website. You need to set src attribute to identify the media source and include a controls attribute so the user can play and pause the media.

How do I make a custom HTML audio tag?

HTML 5 audio tags can be styled. By using the audio tag with “controls” attribute, the default browsers player is used. You can customize by not using the browsers controls. You can also add CSS classes to each one of the elements and style them accordingly.


1 Answers

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>
like image 115
Adam Azad Avatar answered Oct 16 '22 19:10

Adam Azad