搜索了一会儿如何制作音频标签以播放本地机器上的歌曲后,我找到了此解决方案(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);
}
});
和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>
上面的代码对于一个文件看起来不错。问题是,有没有一种好方法可以从输入中加载多个文件,以使音频像播放列表一样播放它们,而无需同时创建FileReader的多个实例?类似于先将文件存储在数组中,然后从该数组中馈送src或音频。
最佳答案
createObjectURL代替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>
关于javascript - HTML5音频播放本地mp3文件的播放列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44167012/