HTML5音频播放本地mp3文件的播放列表 [英] HTML5 Audio to play a playlist of local mp3 files

查看:1447
本文介绍了HTML5音频播放本地mp3文件的播放列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在搜索了如何让音频标签从本地机器播放歌曲之后,我找到了这个解决方案(用html播放音频本地文件):

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);
    }
});

和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或音频。

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.

推荐答案

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>

这篇关于HTML5音频播放本地mp3文件的播放列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆