Reputation: 1849
After searching a while for how to make audio tag to play a song from local machine, I found this solution (Play audio local file with html):
var $audio = $('#myAudio');
$('input').on('change', function(e) {
var target = e.currentTarget;
var file = target.files[0];
var reader = new FileReader();
console.log($audio[0]);
if (target.files && file) {
var reader = new FileReader();
reader.onload = function (e) {
$audio.attr('src', e.target.result);
$audio.play();
}
reader.readAsDataURL(file);
}
});
And html:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file">
<audio controls id="myAudio" autoplay></audio>
The above code looks good for one file. The question is that is there a good way to load multiple files from input to make the audio play them like a playlist, without creating multiple instances of FileReader simultaneously? Something like storing the files in array first, and then feeding src or audio from that array.
Upvotes: 0
Views: 8325
Reputation: 4370
createObjectURL instead of new FileReader()
var songs = document.getElementById("songs"),
myAudio = document.getElementById("myAudio");
function next(n){
var url = URL.createObjectURL(files[n]);
myAudio.setAttribute('src', url);
myAudio.play();
}
var _next = 0,
files,
len;
songs.addEventListener('change', function() {
files = songs.files;
len = files.length;
if(len){
next(_next);
}
});
myAudio.addEventListener("ended", function(){
_next += 1;
next(_next);
console.log(len, _next);
if((len-1)==_next){
_next=-1;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="songs" multiple>
<audio controls id="myAudio" autoplay></audio>
Upvotes: 8