简体   繁体   English

如何使用javascript或jquery单击按钮使多个mp3文件一个接一个播放?

[英]How to make multiple mp3 files play one after another on the click of a button using javascript or jquery?

I have the following html and script to play/pause an audio by clicking a button.我有以下 html 和脚本可以通过单击按钮来播放/暂停音频。

<audio id="testAudio" hidden src="sample.mp3" type="audio/mpeg">
</audio>

<button id="playAudio">Play</button>


<script>
document.getElementById("playAudio").addEventListener("click", function(){
    var audio = document.getElementById('testAudio');
  if(this.className == 'is-playing'){
    this.className = "";
    this.innerHTML = "Play"
    audio.pause();
  }else{
    this.className = "is-playing";
    this.innerHTML = "Pause";
    audio.play();
  }

});
</script>

I need to edit it in such a way as to play multiple mp3 files one by one in a defined order and stop only when the last audio has played.我需要对其进行编辑,以便按照定义的顺序一个一个地播放多个 mp3 文件,并且仅在播放最后一个音频时停止。

I just don't know how to make that work.我只是不知道如何使它起作用。 Can anyone help?任何人都可以帮忙吗?

You can register an event handler for the audio tag, that first when the current file has finished;您可以为音频标签注册一个事件处理程序,首先是在当前文件完成后;

document.getElementById("testAudio").addEventListener("ended",function(e) {
  // Play next track 
});

If you have a list of tracks to play in an array, then simply play the next one after the current track has finished.如果您有一个要在数组中播放的曲目列表,则只需在当前曲目结束后播放下一个曲目即可。 Using the setTimeout function you can put in a delay between the tracks.使用 setTimeout 函数,您可以在曲目之间设置延迟。 A simple example is as follows;一个简单的例子如下;

<script>
var playlist= [
  'https://api.twilio.com/cowbell.mp3',
  'https://demo.twilio.com/hellomonkey/monkey.mp3'
];
var currentTrackIndex = 0;    
var delayBetweenTracks = 2000;

document.getElementById("playAudio").addEventListener("click", function(){  
  var audio = document.getElementById('testAudio');
  if(this.className == 'is-playing'){
    this.className = "";
    this.innerHTML = "Play"
    audio.pause();
  }else{
    this.className = "is-playing";
    this.innerHTML = "Pause";
    audio.play();
  }
});

document.getElementById("testAudio").addEventListener("ended",function(e) {
  var audio = document.getElementById('testAudio');      
  setTimeout(function() { 
    currentTrackIndex++;
    if (currentTrackIndex < playlist.length) { 
      audio.src = playlist[currentTrackIndex];
      audio.play();
    }
  }, delayBetweenTracks);
});
</script>

Note that cowbell track is 52 seconds long, so if your testing the above (for your own sanity) set the controls property to the audio tag so you can skip through most of it.请注意,牛铃音轨的长度为 52 秒,因此如果您测试上述内容(为了您自己的理智),请将控件属性设置为音频标签,这样您就可以跳过其中的大部分内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM