关于 javascript:在我的 HTML 页面中使用 JS 播放器播放声音一定次数 | 珊瑚贝

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()
});
  • 如何重复 html5 音频的可能重复项


html audio 元素没有提供任何属性来确定它应该播放音频的次数。

解决它的一种方法是使用计数器并将事件侦听器附加到 html audio 元素的 ended 事件。每次播放完成时,都会执行事件侦听器,您可以在其中减少计数器并再次播放音频。

一旦计数器达到 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” />


来源:https://www.codenong.com/55591193/

微信公众号
手机浏览(小程序)

Warning: get_headers(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(): Failed to enable crypto in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(https://static.shanhubei.com/qrcode/qrcode_viewid_9697.jpg): failed to open stream: operation failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57
0
分享到:
没有账号? 忘记密码?