2017-09-29 144 views
1

這是我的第一篇文章,我已經搜索了一點答案,但還沒有遇到任何解決方案。用javascript onClick開始/停止聲音

基本上我想要做的就是讓onClick =「」用javascript函數啓動和停止音頻,playSound(聲音)。這是迄今爲止我已經結束的。現在,當我單擊時沒有音頻播放,但是當我單獨測試單個代碼'song1.play()'時,聲音播放,但顯示在再次單擊時不會停止。希望這不是太困難。

function playSound(sound){ 
     var song1=document.getElementById(sound); 
     var isPlaying = true; 
     if (!isPlaying){ 
      isPlaying == true; 
      song1.play(); 
     } 
     else{ 
      isPlaying == false; 
      song1.pause(); 
     } 
    } 

回答

0

您正在比較isPlaying變量與true和false,而不是將它們分配給變量。這應該現在工作。

function playSound(sound){ 
    var song1=document.getElementById(sound); 
    var isPlaying = true; 
    if (!isPlaying){ 
     isPlaying = true; 
     song1.play(); 
    } 
    else{ 
     isPlaying = false; 
     song1.pause(); 
    } 
} 
0

您應該使用=代替==

=是賦值運算符,其中作爲==是比較運算。

0

兩個小的更正。

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(); 
      } 
     } 
0

您可以檢查是否健全是使用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>

+0

您好,感謝這一點。事實證明,在html中做腳本只是讓一些事情不起作用。我把它放在一個單獨的js文件中,並將它鏈接到html,它完美地工作,謝謝。 –