跨平台、跨浏览器的 Javascript 声音播放方式?

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

模拟中的一些步骤要求我们播放音频的“画外音”剪辑。我一直无法找到一种简单的方法来跨多个浏览器实现这一点。

Soundmanager 2 非常接近我所需要的,但它只能播放 mp3文件,遗留数据可能包含一些内容。还有 wav 文件。

有人有其他可能有帮助的图书馆吗?

60588 次浏览

我相信最简单和最方便的方式将播放的声音使用一个小的 Flash 剪辑。我很欣赏它不是一个 JavaScript 解决方案,但它是实现你目标的最简单的方法

一些额外的链接从以前的 类似的问题:

如果您正在使用 Prototype,Scriptacful 库 具有完善的 API.jQuery似乎有一个插件也是如此。

您必须包含一个插件,如 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);
}
//======================================================================

如果您正在使用 Mootools,那么就有 MooSound 插件

Dacracot 代码是干净的基本领域,但也许写没有第二个想法? 当然,您首先要检查早期嵌入的存在,然后保存副本 嵌入创造线。

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; en-US; rv: 1.9.0.15) Gecko/2009102814 Ubuntu/8.04(hardy) Firefox/3.0.15在尝试这个时死掉了。

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

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

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

function Play(sound) {
$("#sound_").remove()
$('body').append('<embed id="sound_" autostart="true" hidden="true" src="/static/sound/' + sound + '.wav" />');
}
<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>

有关详细信息,请参阅 http://www.w3schools.com/html/html5_audio.asp

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

对于一个带有 wav 文件的跨浏览器解决方案,我建议使用默认的 <audio>标签,然后使用@dacracot 在 给你之前建议的 <embed>解决方案,如果用户在 IE 中,你可以通过在 SO 中的一个小搜索轻松地检查它。