2013-06-29 259 views
2

我在製作聊天應用程序,其中一個功能是發送聲音。發送的HTML如下:HTML音頻播放/停止

<p> 
    <audio autoplay> 
     <source src="sounds/lol.mp3" type="audio/mpeg"> 
    </audio> 
    LOL 
    <a href="#" id="soundStop">Stop</a> 
    <a href="#" id="soundPlay" style="display:none;">Play</a> 
</p> 

'autoplay'在第一次發送時工作正常。所以現在我需要一個播放/停止鏈接來隨時多次聽到聲音。我有以下的Javascript:

$(document).on('click', '#soundStop', function(e) { 
    $(this).hide(); 
    $(this).next("a").show(); 
    $('audio').each(function(){ 
     this.pause(); 
     this.currentTime = 0; 
    }); 
    e.preventDefault(); 
}); 

$(document).on('click', '#soundPlay', function(e) { 
    $(this).hide(); 
    $(this).prev("a").show(); 
    $(this).closest("audio").play(); 
    //alert("play sound again!"); 
    e.preventDefault(); 
}); 

停止功能的工作(雖然我不知道針對所有的「音頻」元素是一個好主意)。但我堅持如何將音頻元素定位到第二個函數中的.play()。我可能會以完全錯誤的方式去做這件事?

任何幫助或建議表示讚賞。

編輯:只是爲了澄清,可能有這些聲音的多個實例得到發送,這就是爲什麼我需要一種方法,只針對每個特定的'音頻'。

回答

4

爲什麼不使用準備使用音頻標籤的控件?它會滿足你的目的。

試試這個代碼:

<!DOCTYPE html> 
<html> 
<body> 
    <audio autoplay controls> 
     <source src="horse.ogg" type="audio/ogg"> 
    </audio> 

</body> 
</html> 

客戶控制

<!DOCTYPE html> 
<html> 
<body> 
<audio id="player" src="horse.ogg"></audio> 
<div> 
    <button onclick="document.getElementById('player').play()">Play</button> 
    <button onclick="document.getElementById('player').pause()">Pause</button> 
    <button onclick="document.getElementById('player').volume+=0.1">Volume Up</button> 
    <button onclick="document.getElementById('player').volume-=0.1">Volume Down</button> 
</div> 
</body> 
</html> 
+0

會的工作,但我需要自定義的控制,所以我可以樣式。 – user2534723

+0

我得到了自定義播放按鈕的代碼 <!DOCTYPE HTML> Play

+0

感謝您的答覆,但是這並沒有真正適合我提供的代碼。只需要在我提供的jQuery函數中針對特定音頻元素的方式。 – user2534723