2012-01-31 98 views
4

我想在每一行中创建一个带有字符串和按钮(播放声音)的表格,并且每个按钮都会播放不同的声音。用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')"> 

写的fil e 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> 

,它仍然不能播放声音。

回答

5

可以实现它如下:

指博客How to Play a Sound on Click or on 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> 
+0

我编辑我的文章,你可以看看变化? – MTA 2012-01-31 12:12:43

+0

不要忘记检查此页面,因为该解决方案删除了​​与锚点关联的文本:http://forum.codecall.net/topic/49572-play-sound-on-click/ – dialex 2013-03-02 14:01:11

1

注意:这不是HTML5。 您可以通过thissound.src获取源代码。然后,您可以将它添加到DOM中,无论您想要放置在哪个位置。

0

你可以使用JavaScript框架,使你的代码更容易。在Scriptaculous的网页看看:

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

据我所知,“jQuery的”没有这么齐全的声音,但是,我想,就表示该插件。

然后你可以把你的声音文件作为链接或'rel'链接,在按钮上放置观察者,并用非常干净的HTML和一些脚本来播放它们。