How to play many audio files in sequence

淺唱寂寞╮ 提交于 2020-04-14 04:42:20

问题


I have several long stories which for which the source audio is sentence-by-sentence audio files. I would like to create a web page where one could listen to individual sentences of a particular story many times, or listen to the whole story from start to finish.

To start, my web page has many <audio> elements, each of which is in a <p> with the corresponding text. Each of these <audio> elements corresponds to a single sentence of the story.

I was about to start coding up a javascript object which was going to allow some sort of "play all" functionality, you'd click the button and it would play audio[0], when that finished, audio[1], etc. It would also have a 'pause' button and keep track of where you were, etc. This way the individual sentences could still be played or enjoyed because they each have an audio element. Or, one could use my "play all" buttons at the top to treat the sequence of audio elements as if they were one big element.

Then I started asking myself if there's some better/easier/more canonical solution here. One thing I thought of doing would be to cat all of these individual audio files together into a big audio file and perhaps create 'chapter' <track> elements. Is this preferable?

What are the pros and cons to each approach? Is there some out-of-the-box solution already made for me which I simply haven't turned up?


回答1:


You could use the ended event to play the next sound when the previous sound completes (Playing HTML 5 Audio sequentially via Javascript):

var sounds = new Array(new Audio("1.mp3"), new Audio("2.mp3"));
var i = -1;
playSnd();

function playSnd() {
    i++;
    if (i == sounds.length) return;
    sounds[i].addEventListener('ended', playSnd);
    sounds[i].play();
}



回答2:


I use javascript to solve the problem, using Audio objects and a setInterval. Below an example:

  var sndLetItSnow = new Audio("audio/letItSnow.m4a");
  var sndSanta = new Audio("audio/snow.m4a");

  var playlist = [sndLetItSnow, sndSanta];

  var current = null;
  var idx = 0;

  function playSound() {
      if (current === null || current.ended) {
          // go to next
          current = playlist[idx++];

          // check if is the last of playlist and return to first
          if (idx >= playlist.length)
              idx = 0;

           // return to begin
           current.currentTime=0;

           // play
           current.play();
      }

  }

  setInterval(playSound, 1000);

For more documentation on Audio object you can visit this page:

https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement

I hope this help!



来源:https://stackoverflow.com/questions/38560764/how-to-play-many-audio-files-in-sequence

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!