簡體   English   中英

用javascript播放聲音

[英]Play sound with javascript

我想在每一行創建一個帶有字符串和按鈕(播放聲音)的表格,每個按鈕播放不同的聲音。

我想用這種方法做到這一點:

<script>
function EvalSound(soundobj) {
  var thissound=document.getElementById(soundobj);
  thissound.Play();
}
</script>

<embed src="success.wav" autostart=false width=1 height=1 id="sound1"
enablejavascript="true">

這是按鈕:

<form>
<input type="button" value="Play Sound" onClick="EvalSound('sound1')">
</form>

問題是我想要在這里:

<input type="button" value="Play Sound" onClick="EvalSound('sound1')">

寫入文件URL而不是'sound1',可以這樣做嗎? 或者我需要更改代碼中的其他內容?

編輯:

我像這樣構建腳本:

<script>
   function EvalSound(soundobj) {
   var embed = document.createElement('embed');
   embed.setAttribute('width',1);
   embed.setAttribute('height',1);
   embed.setAttribute('src',soundobj);
   embed.setAttribute('autostart', false);
   embed.setAttribute('enablejavascript', true);
   embed.Play();
   }
</script>

並稱之為:

<form>
    <input type="button" value="Play Sound" onClick="EvalSound('sound url')">
</form>

它仍然沒有發出聲音。

您可以按照以下方式實現:

請參閱博客如何在Click或MouseOver上播放聲音

<script language="javascript" type="text/javascript">
 function playSound(soundfile) {
 document.getElementById("dummy").innerHTML=
 "<embed src=\""+soundfile+"\" hidden=\"true\" autostart=\"true\" loop=\"false\" />";
 }
 </script>

在網頁中

<span id="dummy"></span>
<a href="#" onclick="playSound('URL to soundfile');">Click here to hear a sound</a>

 <p onmouseover="playSound('URL to soundfile');">Mouse over this text to hear a sound</p>

注意:這不是HTML5。 您可以使用thissound.src獲取源thissound.src 然后,您可以將它添加到DOM中,無論您想要放在哪個位置。

您可以使用javascript框架來簡化代碼。 看一下Scriptaculous頁面:

http://madrobby.github.com/scriptaculous/sound/

據我所知,'jQuery'的聲音不是很好,但是,我想有插件可供選擇。

然后你可以把你的聲音文件作為鏈接或'rel'鏈接,在按鈕上有觀察者,並用非常干凈的HTML和一些腳本來播放它們。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM