这是我的第一篇文章,我已经搜索了答案,但没有遇到任何解决方案。
基本上我要做的就是通过JavaScript函数启动和停止音频,弹奏(声音)。这是我到目前为止结束的。现在,当我单击时没有音频播放,但是当我本身测试单个代码'song1.play()'时,声音会播放,但是显然,再次单击时不会停止。希望这不是太困难。
function playSound(sound){
var song1=document.getElementById(sound);
var isPlaying = true;
if (!isPlaying){
isPlaying == true;
song1.play();
}
else{
isPlaying == false;
song1.pause();
}
}
两个小更正。
a)var isPlaying = true;
应在全球声明,以在" onClick"的多个调用之间保留其值。
b)在``Isplaying''变量的分配语句中应将==
更改为=
。
var isPlaying = true;
function playSound(sound){
var song1=document.getElementById(sound);
if (!isPlaying){
isPlaying = true;
song1.play();
}
else{
isPlaying = false;
song1.pause();
}
}
您将ISPlay变量与True和False进行比较,而不是将它们分配给变量。现在应该起作用。
function playSound(sound){
var song1=document.getElementById(sound);
var isPlaying = true;
if (!isPlaying){
isPlaying = true;
song1.play();
}
else{
isPlaying = false;
song1.pause();
}
}
您应该使用= ==
=是分配运算符,其中==是比较操作员。
您可以使用paused
属性检查声音是否暂停:
function playSound(sound) {
var song1 = document.getElementById(sound);
song1.volume = .25; // setting the volume to 25% because the sound is loud
if (song1.paused) { // if song1 is paused
song1.play();
} else {
song1.pause();
}
}
<audio id="sound">
<source src="https://www.w3schools.com/TagS/horse.mp3" type="audio/mp3">
</audio>
<button onclick="playSound('sound')">Play/Pause</button>