播放列表与jQuery

时间:2016-08-17 11:03:25

标签: javascript jquery dom html5-audio

我有一首有两首歌曲的播放列表,但每次播放时都只播放第一首歌曲。我无法弄清楚问题所在。每次用户点击错误的答案时,我都会尝试创建一个测验,播放两首歌曲。

我的代码:

$(stage).append('<div id="play"><audio id="bg_audio">
    <source src="../Voices/check_answer.ogg"></source>
    <source src="../Voices/good.ogg"></source></audio>
    </div>'); 
$('.pix').click(function() {
    if(questionLock==false) {
        if(this.id!=rnd) {
            $('#bg_audio').get(0).play();
        } else {
            questionLock=true;  
            setTimeout(function(){changeQuestion()},1000);
            $('.displayed', stage).addClass('hidden');
        }
    }})
}

1 个答案:

答案 0 :(得分:0)

您误解了<source>标记的工作原理。它旨在以不同的格式提供相同的音频文件,而不是创建要播放的音频文件列表。

如果您只想播放音频而不显示控件,则可以使用Audio constructor代替创建HTML元素并将其附加到页面。

// Take a list of files as arguments.
const playList = (...list) => {
  // Stop recursion when the list is empty.
  if (list.length === 0) return Promise.resolve()
  return new Promise((resolve, reject) => {
    // Create a new Audio element from the first item on the list.
    const audio = new Audio(list.shift())
    // Resolve the promise after the file ends playing.
    audio.addEventListener('ended', () => resolve(...list))
    // Reject the promise if the file fails to load.
    audio.addEventListener('error', () => reject('Resource failed to load.'))
    // Play the audio.
    audio.play()
  // Continue playing the rest of list recursively.
  }).then(playList)
}

// For simplicity, play the same file twice.
playList(
  'http://www.html5tutorial.info/media/vincent.mp3'
 ,'http://www.html5tutorial.info/media/vincent.mp3'
)