跨平台,跨浏览器的方式来播放Java脚本中的声音?

问题描述 投票:78回答:10

我正在编写一个dhtml应用程序,该应用程序创建系统的交互式仿真。用于仿真的数据是从另一个工具生成的,并且已经有大量的旧数据。

模拟中的某些步骤要求我们播放音频的“旁白”片段。我一直找不到在多个浏览器上完成此操作的简便方法。

Soundmanager2非常接近我的需求,但是它将仅播放mp3文件,并且旧数据也可能包含一些.wav文件。

任何人还有其他可能有用的库吗?

javascript audio cross-browser cross-platform dhtml
10个回答
61
投票

您将必须包含Real Audio或QuickTime之类的插件来处理.wav文件,但这应该可以工作...

//======================================================================
var soundEmbed = null;
//======================================================================
function soundPlay(which)
    {
    if (!soundEmbed)
        {
        soundEmbed = document.createElement("embed");
        soundEmbed.setAttribute("src", "/snd/"+which+".wav");
        soundEmbed.setAttribute("hidden", true);
        soundEmbed.setAttribute("autostart", true);
        }
    else
        {
        document.body.removeChild(soundEmbed);
        soundEmbed.removed = true;
        soundEmbed = null;
        soundEmbed = document.createElement("embed");
        soundEmbed.setAttribute("src", "/snd/"+which+".wav");
        soundEmbed.setAttribute("hidden", true);
        soundEmbed.setAttribute("autostart", true);
        }
    soundEmbed.removed = false;
    document.body.appendChild(soundEmbed);
    }
//======================================================================

0
投票

对于带有wav文件的跨浏览器解决方案,我建议将<audio>标签设置为默认值,然后使用@dacracot在<embed>之前建议的here解决方案,如果用户使用的是IE,则可以轻松检查它在SO中进行一点搜索。


9
投票

如果使用的是原型,则为脚本库has a sound API。 jQuery appears to have a plugin也是。


8
投票

dacracots代码是干净的基本dom,但是编写时可能没有经过深思熟虑?当然,您首先要检查较早嵌入的存在,然后保存重复的嵌入创作线。

var soundEmbed = null;
//=====================================================================

function soundPlay(which)
{
    if (soundEmbed)
       document.body.removeChild(soundEmbed);
    soundEmbed = document.createElement("embed");
    soundEmbed.setAttribute("src", "/snd/"+which+".wav");
    soundEmbed.setAttribute("hidden", true);
    soundEmbed.setAttribute("autostart", true);
    document.body.appendChild(soundEmbed);
}

在扫描某种相似情况的解决方案时,请多加思考。不幸的是,我的浏览器Mozilla / 5.0(X11; U; Linux i686; zh-CN; rv:1.9.0.15)Gecko / 2009102814 Ubuntu / 8.04(hardy)Firefox / 3.0.15在尝试此操作时死了。

安装最新更新后,Firefox仍然崩溃,Opera仍然存在。


7
投票

我相信最简单,最方便的方法就是使用小型Flash剪辑播放声音。我赞赏这不是JavaScript解决方案,但它是实现目标的最简单方法。

上一个similar question中的一些额外链接:


5
投票

我喜欢dacracot的答案...这是jQuery中的类似解决方案:


4
投票

您可以使用HTML5 <audio>标签。


3
投票

如果使用Mootools,则有MooSound plugin


3
投票
<audio controls>
  <source src="horse.ogg" type="audio/ogg">
  <source src="horse.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>

1
投票

有一个比这要简单得多的解决方案,而不必求助于插件。 IE具有自己的bgsound属性,还有另一种方法可以使它适用于所有其他浏览器。在这里查看我的教程= http://www.andy-howard.com/how-to-play-sounds-cross-browser-including-ie/index.html

© www.soinside.com 2019 - 2024. All rights reserved.