【问题标题】:Playlist with jQuery带有 jQ​​uery 的播放列表
【发布时间】:2016-12-24 00:07:00
【问题描述】:

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

我的代码:

$(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');
        }
    }})
}

【问题讨论】:

  • 使用您提供的代码,我们“也无法找出问题所在”。请发布可以测试的代码。一个 JSFiddle 也会是一个不错的附加功能。
  • 第二个,你能试着分解一下我们应该查看的代码部分吗?

标签: javascript jquery dom html5-audio


【解决方案1】:

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

如果您只想播放音频而不显示控件,则可以使用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'
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-16
    • 2014-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-08
    • 2018-02-20
    相关资源
    最近更新 更多