Play sound a set number of times with JS player in my HTML page
我想让声音播放 3 次,然后在我的 html 页面中停止,如果我启用循环为真,它会继续循环,如果它是假的,它会播放 1x。
我的代码现在看起来像这样,有人可以建议吗?
1 2 3 4 5 6 7 | var popupAudioPlayer = document.getElementById('popup_sound'); scene.on("enter", function (event) { popupAudioPlayer.currentTime = 0; popupAudioPlayer.loop = true; popupAudioPlayer.playthroughs = 3; popupAudioPlayer.play() }); |
html
解决它的一种方法是使用计数器并将事件侦听器附加到 html
一旦计数器达到 0,就删除事件监听器。
像这样:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | var popupAudioPlayer = document.getElementById('popup_sound'); var scene = document.getElementById('scene'); scene.addEventListener("click", function (event) { let counter = 3; const customPlay = function() { popupAudioPlayer.play(); counter--; if (counter === 0) { popupAudioPlayer.removeEventListener('ended', customPlay); } }; popupAudioPlayer.addEventListener('ended', customPlay); popupAudioPlayer.currentTime = 0; popupAudioPlayer.loop = false; customPlay(); }); |
1 2 3 4 5 6 7 | <button id="scene"> Play me 3 times </button> <audio id="popup_sound" src="https://www.soundeffectsplus.com/uploads/prod_audio/41802331_bow-arrow-hit-target-01.mp3" /> |