如何使用相同的功能播放和停止音频两次



我正在做一个心理健康网站,里面有一个冥想区。有两个div卡和内部的每个,有一个按钮,播放和停止音乐时点击。

我在html文件中使用脚本标签来获取额外的信息。

目的:当点击两个卡片div中的每个按钮时,应该会播放指导冥想的音频。有一个长音频和一个短音频,有mp3和ogg两种格式。

问题:其中一个音频播放得很好,但另一个不行。这意味着它不会播放,并停止当按钮被点击。你能检查一下并告诉我哪里出了问题吗?

<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>
<script>
const rollSound = document.getElementById('rollSound');
const btn = document.getElementById('play');
btn.addEventListener("click", e => rollSound.paused ? rollSound.play() : rollSound.pause());

</script>
</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>
<script>
const shortsound = document.getElementById('shortsound');
const btn = document.getElementById('roll');
btn.addEventListener("click", e => shortsound.paused ? shortsound.play() : shortsound.pause());

</script>
</div>

执行脚本时出现错误,因为您不能第二次声明var btn =

改为

const shortsound = document.getElementById('shortsound');
const btn = document.getElementById('roll');
btn.addEventListener("click", e => shortsound.paused ? shortsound.play() : shortsound.pause());

变成这样:

const shortsound = document.getElementById('shortsound');
const btn2 = document.getElementById('roll');
btn2.addEventListener("click", e => shortsound.paused ? shortsound.play() : shortsound.pause());

,它将工作,看看这个jsfiddle:

https://jsfiddle.net/snw3950L/1/

最新更新