【发布时间】:2021-10-19 23:23:51
【问题描述】:
我有两个使用 js 的按钮播放和停止的冥想音乐。问题是如果一个播放,另一个在点击时也会播放。
我希望一个在单击另一个时停止播放。我正在学习布尔值。有没有办法使用布尔值来做到这一点?
<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 btn2 = document.getElementById('roll');
btn2.addEventListener("click", e => shortsound.paused ? shortsound.play() : shortsound.pause());
</script>
<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) {
soundToPlay.paused ? soundToPlay.play() : soundPlay.pause()
soundToPause.pause()
}
btn.addEventListener("click", () => playOneSound(rollSoundEl, shortsoundEl));
btn2.addEventListener("click", () => playOneSound(shortsoundEl, rollSoundEl));
</script>
</div>
</div> <!--main-box-->
【问题讨论】:
标签: javascript html audio boolean