在搜索了如何让音频标签从本地机器播放歌曲之后,我找到了这个解决方案(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或音频。
答案 0 :(得分:2)
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;
}
});
&#13;
<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>
&#13;