2014-04-08 53 views
1

我有這個代碼,在按鈕上按下它播放聲音,我想要的是當一個聲音從第一次點擊播放時,如果你點擊另一個按鈕之前,它停止第一個和播放下一個你點擊。Javascript播放聲音點擊,第二個按鈕單擊停止第一個聲音

任何想法都會很棒。

<!DOCTYPE html> 
<head> 
<title>Sounds</title> 
</head> 

<body> 

<audio id="sound1" src="sounds/sound1.mp3"></audio> 
<audio id="sound2" src="sounds/sound2.mp3"></audio> 

<button onclick="document.getElementById('sound1').play()">Sound 1</button><br /> 
<button onclick="document.getElementById('sound2').play()">Sound 2</button><br /> 

</body> 
</html> 

在此先感謝。

回答

4

嘗試類似的東西:

<audio id="sound1" src="sounds/sound1.mp3"></audio> 
<audio id="sound2" src="sounds/sound2.mp3"></audio> 

<button onclick="playSound1()">Sound 1</button><br /> 
<button onclick="playSound2()">Sound 2</button><br /> 

<script type="text/javascript"> 
var audio1 = document.getElementById('sound1'); 
var audio2 = document.getElementById('sound2'); 
function playSound1(){ 
if (audio1.paused !== true){ 
    audio1.pause(); 
    audio2.play(); 
    } 
else{ 
    audio2.play(); 
    } 
} 
function playSound2(){ 
if (audio2.paused !== true){ 
    audio2.pause(); 
    audio1.play(); 
    } 
else{ 
    audio1.play(); 
    } 
} 
</script> 

雖然我建議你在按鈕標籤上使用addEventListener方法,而不是onclick屬性,因爲它更易於維護。

謝謝

0

將相應音頻的ID放入按鈕上的data-target屬性中。在負載,獲得按鈕並指定一個點擊處理程序 重新加載當前的音頻,將當前音頻元素按鈕的目標,並播放當前的音響

相關問題