如何使用html5和jQuery播放所有音频源

How to play all audio sources with html5 and jQuery

本文关键字:音频 播放 jQuery 何使用 html5      更新时间:2023-09-26

我正在尝试仅使用html5和jQuery制作一个简单的音频播放器。当我想播放一个文件/流时,或者当我单击下一个/预览或播放列表中的另一个文件时,它效果很好。

但是我需要一个可以自动播放播放列表中所有文件的播放器。

我尝试

了$.each(),我尝试了一个回避函数...但没有成功...

我可以在这里显示一部分代码:

var el = $('#playerbox');
var soundType = el.data('page-soundtype');
var soundFile = el.data('page-soundfile');
var soundFiles = el.data('page-soundfiles');//playlist, paths to sources
var audio = $("<audio preload />");
//make 2 types of sources for different browsers:
var source1= $('<source />').attr('type', 'audio/mpeg');  // original, mp3 format
var source2= $('<source />').attr('type', 'audio/ogg'); // a copy, ogg format
audio.append(source1).append(source2);
el.append(audio);
var player=audio[0];
player.volume=0;
var i=0; //The play list counter, in case we have it
var op={}; //player options
var runPlayer = function(op){
    var fadetime = (op.fadetime || 1000);
    player.oncanplay = function(){
        player.play();
        audio.animate({volume: 1}, fadetime);
    }
    if(soundType === 'list'){
        player.addEventListener('ended', function(){
            i++;
            if(soundFiles[i].length>0){
                source1.attr('src', soundFiles[i]);
                source2.attr('src', soundFiles[i].replace(".mp3", ".ogg"));
                op.fadetime = 1500;
                player.pause();
                runPlayer(op);
            }
        }, false)
       }
}
//set sources
if(soundType==='list' && $.isArray(soundFiles)){
    //prepare playlist
    source1.attr('src', soundFiles[i]);
    source2.attr('src', soundFiles[i].replace(".mp3", ".ogg"));
    op.fadetime = 1;            
}
else if(soundType==='sound'){
    //prepare sound
    source1.attr('src', soundFile);
    source2.attr('src', soundFile.replace(".mp3", ".ogg"));
}
runPlayer(op);
因此,第一个音频源播放

良好,然后第二个音频源加载到播放器的"src",但无法播放:(

我的错误在哪里?谢谢。

加载新的 src 后,您必须在该元素上调用 .play()

以下是如何播放队列中所有音频文件的示例

var el = $('#playerbox'); //assuming here that el is your <audio> element
var audioSources = [song1.mp3, song2.mp3....]// here is your array of filenames
var index = 0;
function playNext(index){
  el.attr('src', audioSources[index]);
  el.play(); //this will play the element
  el.on('ended', function(){ //this will bind a function to the "ended" event
    //increment the index to target the next element
    index++;
    if(index < audioSources.length){
      //plays the next song and binds the function to the ended event again until the queue is empty
      playNext(index);          
    }
  }
}
playNext(index);

这对你有用吗?