用javascript播放声音

MTA*_*MTA 4 html javascript html5

我想在每一行创建一个带有字符串和按钮(播放声音)的表格,每个按钮播放不同的声音.

我想用这种方法做到这一点:

<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">
Run Code Online (Sandbox Code Playgroud)

这是按钮:

<form>
<input type="button" value="Play Sound" onClick="EvalSound('sound1')">
</form>
Run Code Online (Sandbox Code Playgroud)

问题是我想要在这里:

<input type="button" value="Play Sound" onClick="EvalSound('sound1')">
Run Code Online (Sandbox Code Playgroud)

写入文件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>
Run Code Online (Sandbox Code Playgroud)

并称之为:

<form>
    <input type="button" value="Play Sound" onClick="EvalSound('sound url')">
</form>
Run Code Online (Sandbox Code Playgroud)

它仍然没有发出声音.

Hem*_*lia 5

您可以按照以下方式实现:

请参阅博客如何在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>
Run Code Online (Sandbox Code Playgroud)

在网页中

<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>
Run Code Online (Sandbox Code Playgroud)