【问题标题】:how do I play and stop an audio twice using the same function如何使用相同的功能两次播放和停止音频
【发布时间】:2021-08-17 07:30:35
【问题描述】:

我正在制作一个心理健康网站,其中有一个冥想区。有两张 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>

【问题讨论】:

  • btn 已在您的第一个 &lt;script&gt; 中声明。您不能在第二次再次声明它。
  • 你好,我改了,还是不行

标签: javascript html audio


【解决方案1】:

执行脚本时出错,因为您无法再次声明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/

【讨论】:

  • 这工作谢谢你。我赞成你的回答
猜你喜欢
  • 2012-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-02
  • 1970-01-01
相关资源
最近更新 更多