【问题标题】:Play sound with javascript用 javascript 播放声音
【发布时间】:2012-01-31 11:42:15
【问题描述】:

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

我想用这个方法来做:

<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>

它仍然没有播放声音。

【问题讨论】:

    标签: javascript html


    【解决方案1】:

    您可以通过以下方式实现:

    参考博客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>
    

    【讨论】:

    【解决方案2】:

    注意:这不是 HTML5。 您可以通过thissound.src 获取源代码。然后,您可以将其添加到 DOM 中您想要放置的任何位置。

    【讨论】:

      【解决方案3】:

      您可以使用 javascript 框架来简化您的代码。看看 Scriptaculous 页面:

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

      据我所知,'jQuery' 在声音方面并不是那么好,但是,我想有一些插件可以做到这一点。

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

      【讨论】:

        猜你喜欢
        • 2011-03-25
        • 1970-01-01
        • 2013-02-01
        • 2021-05-31
        • 2022-08-05
        • 1970-01-01
        • 2010-10-01
        • 1970-01-01
        • 2013-10-30
        相关资源
        最近更新 更多