简体   繁体   中英

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.

<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.

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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