2008-10-09 135 views
79

我在写一个创建系统交互式模拟的dhtml应用程序。用于模拟的数据是从另一个工具生成的,并且已经有大量的遗留数据。跨平台,跨浏览器的方式来播放Javascript的声音?

模拟中的某些步骤需要我们播放音频的“配音”剪辑。我一直无法找到一种简单的方法在多个浏览器中完成此操作。

Soundmanager2非常接近我所需要的,但它只会播放mp3文件,并且遗留数据也可能包含一些.wav文件。

有没有人有任何其他库可能有帮助?

+5

很高兴你找到你的解决方案,但独立于此,你可能想考虑将这些.wav文件转换为.mp3文件。如果稍微降低音质,您可以从波形文件大小的1/3到1/10的任何位置获得文件大小。在播放声音时可能会让事情更有响应。 – infocyde 2010-09-13 18:35:23

回答

62

您必须包括一个插件,如Real音频或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); 
    } 
//====================================================================== 
+14

我从来不理解赞成票。这工作。我已将它部署在我的应用程序中。为什么它值得投票? – dacracot 2008-10-09 17:02:01

+1

作为问这个问题的人,我也想知道。对我来说,这看起来是一个很好的/简单的解决方案。有人会评论什么是错的吗? – 2008-10-09 17:57:40

+2

我不知道你为什么被拒绝,可能是因为使用了“真正的音频”或“quicktime”这两个词。也许那个贬低你的人不知道它是如何完成的?至于我,+1,你的代码几乎与jQuery插件中使用的代码大致相同,只是在最接受的答案中声明的代码... – karlipoppins 2008-10-23 15:59:43

8

我相信最简单最方便的方法就是使用小型Flash剪辑播放声音。我很欣赏它不是一个JavaScript的解决方案,但它是为了实现自己的目标

从以前similar question一些额外的链接最简单的方法:

+1

但我找不到任何将播放WAV文件的Flash解决方案。它出现闪光灯只支持MP3。 我会看看scriptaculous的插件,但我讨厌为这个功能包含一个额外的库。 – 2008-10-09 15:59:56

9

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

安装最新的更新后,Firefox仍然崩溃,歌剧保持活着。

5

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

6

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

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