单击时如何使HTML5音频播放一次?

时间:2015-04-04 14:40:24

标签: html html5 audio html5-audio

我正在对综合语音进行在线评估调查。部分测试要求只允许听众听到给定的WAV文件播放一次(作为实验控件)。

我已经想出如何简单地嵌入带控件的音频剪辑,以便可以多次播放:

    <audio controls>
    <source src="http://mypage.com/my_sound.wav" type="audio/wav">
    Your browser does not support the audio element
    </audio>

此外,我已经看到一些HTML问题试图解决HTML音频只播放一次的错误:

Audio played once only in Google Chrome in html

JavaScript + HTML5: Audio will only play once under certain circumstances

但是,我的问题是如何编写此代码(只需点击一次即可播放HTML音频)?我所看到的一切都将其视为一个需要修复的错误,而不是一个故意的目标。

干杯!

1 个答案:

答案 0 :(得分:0)

我也一直在寻找这个。

您有几个选择。

这个停止的关键是被发生的事件,正如你所料,当肥胖女士停止唱歌时触发。

<audio id="gilda">
  <source url="epic-aria.mp3">
</audio>

var fatLady = document.getElementById('gilda');
fatLady.onended = function() {
  fatLady.pause();
  fatLady.currentTime = 0; // << only needed if you're cutting off the sound misstep (before the end) and need to return to the beginning - but you might need it. Since you are doing some gaming, I figured that might come up...
};

还有一种jQuery方式,我目前正在使用它。 jQuery没有使用onended,但是 - 它使用了end而不是......

var fatLady = $('#gilda');
fatLady.bind('ended', function(event) {
  fatLady
    .pause()
    .currentTime = 0; // << haven't field-tested this yet, but jquery didn't yell at me about it.

});

如果您遇到任何打嗝,请告诉我。

相关问题