如何使用布尔值实现点击播放冥想音频时自动停止另一音频播放
问题原因
你现在的代码给每个按钮重复绑定了2次点击事件:
- 第一次是每个slot里单独写的点击逻辑,只会控制对应音频的播放暂停
- 第二次是底部统一写的
playOneSound绑定的事件
点击按钮时两次事件逻辑先后触发,才会出现同时播放的问题,同时你写的playOneSound函数里还有拼写错误:soundPlay是不存在的变量,应该是soundToPlay。
是否可以通过布尔值实现功能?
当然可以,布尔值的核心作用就是记录「是/否」的二元状态,刚好可以用来标记音频的播放状态。实际上<audio>元素自带的paused属性本身就是布尔值,你完全可以直接用这个原生属性实现需求,不需要额外自定义布尔变量。
修复后的完整代码
你可以删掉每个slot里单独绑定的那两段点击事件代码,只保留最后一段公共逻辑、修正拼写错误即可,修改后代码如下:
<div class="main-box"> <div class="slot1"> <p class="line line1">this is the long music</p> <audio id="rollSound" loop> <source src="sounds/long-medi.mp3" type="audio/mpeg"> <source src="sounds/long-medi.ogg" type="audio/ogg"> Your browser does not support the sound files. Please proceed by using other solutions. <!--the obove text will only show if the users' browser does not play the two files. --> </audio> <button id="play">play/stop</button> </div> <div class="slot2"> <p class="line line2">this is for short music</p> <audio id="shortsound" loop> <source src="sounds/short-medi.mp3" type="audio/mpeg"> <source src="sounds/short-medi.ogg" type="audio/ogg"> Your browser does not support the sound files. Please proceed by using other solutions. </audio> <button id="roll">play/stop</button> </div> <script> const rollSoundEl = document.getElementById('rollSound'); const shortsoundEl = document.getElementById('shortsound'); const btn = document.getElementById('play'); const btn2 = document.getElementById('roll'); function playOneSound(soundToPlay, soundToPause) { // 先停止另一个音频 soundToPause.pause(); // 再切换当前点击对应音频的播放状态 soundToPlay.paused ? soundToPlay.play() : soundToPlay.pause(); } btn.addEventListener("click", () => playOneSound(rollSoundEl, shortsoundEl)); btn2.addEventListener("click", () => playOneSound(shortsoundEl, rollSoundEl)); </script> </div> <!--main-box-->
内容的提问来源于stack exchange,提问作者monie
相关产品推荐
相关产品推荐

