2013-06-29 62 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