使用JavaScript播放声音

问题描述:

无论我做什么,我都无法在Firefox或IE或Chrome中播放声音。使用JavaScript播放声音

<html> 
<head> 
<script type="text/javascript"> 

    function play() 
{ 
    var embed = document.createElement('object'); 

    embed.setAttribute('src', 'c:\\test.wav'); 
    embed.setAttribute('hidden', true); 
    embed.setAttribute('autostart', true); 
    embed.setAttribute('enablejavascript', true); 

    document.childNodes[0].appendChild(embed); 

} 

// --> 
</script> 
</head> 
<body onload="play();"> 
</body> 
</html> 
+14

**请不要**有背景音乐播放当页面加载时自动。这是一个网页最烦人的事情之一(见http://www.seomoz.org/blog/how-to-convince-a-client-their-site-doesnt-need-music)。至少可以选择将其静音。 – 2010-08-04 05:33:31

+2

你的问题之一是'\ t'是选项卡。 – 2010-08-04 05:33:40

+0

修正了\ t的事情,但仍然没有运气。 – FaNIX 2010-08-04 05:39:35

尝试使用的功能发挥()

function play() 
{ 
    var embed=document.createElement('object'); 
    embed.setAttribute('type','audio/wav'); 
    embed.setAttribute('data', 'c:\test.wav'); 
    embed.setAttribute('autostart', true); 
    document.getElementsByTagName('body')[0].appendChild(embed); 
} 

与您的代码的问题是你使用src属性,这对于<嵌入>标签这个修订版本。而是使用<对象>标记的数据属性。



如果您试图从中获得最大的兼容性,您还应该考虑添加嵌入标记作为对象标记的替代方法。它的工作方式是这样的:

<object data="test.wav" type="audio/wav" autostart="true"> 
<embed src="test.wav" autostart="true" alt="Could not load audio" /> 
</object> 

的使用方法类似noscript标记,在旧的浏览器不支持object标签诉诸嵌入标签。

+0

不,这似乎也没有播放文件.... – FaNIX 2010-08-04 05:49:39

+0

你确定你有一个有效的WAV文件?我在发布之前在计算机上测试了我的代码,并且它在Google Chrome上完美运行。尝试将test.wav文件放在与html文件相同的目录中,并将data属性设置为'test.wav'。另外,你能否让我知道你正在使用哪个浏览器,这样我可以检查自己? – Kranu 2010-08-04 06:16:02

+0

好吧,我将文件移至相同的文件夹,它使用谷歌浏览器,但不与Firefox。我其实只需要它在Firefox中工作。 – FaNIX 2010-08-04 06:19:18

使用<embed>标签的FYI将使您的代码无效。目前你有两种选择,如果你想播放你的网页上的声音:[1]使用这种方法,它适用于大多数浏览器,但会使HTML失效(使用<embed>)或[2]使用只能在某些最新浏览器中使用的方法,但是这将是未来的方式,也被认为是有效的HTML(使用<audio><object>)。

试试这个方法,在所有的浏览器来播放声音:

function playSound(soundfile_ogg, soundfile_mp, soundfile_ma) { 
    if ("Audio" in window) { 
     var a = new Audio(); 
     if (!!(a.canPlayType && a.canPlayType('audio/ogg; codecs="vorbis"') 
       .replace(/no/, ''))) 
      a.src = soundfile_ogg; 
     else if (!!(a.canPlayType && a.canPlayType('audio/mpeg;').replace(/no/, 
       ''))) 
      a.src = soundfile_mp; 
     else if (!!(a.canPlayType && a.canPlayType(
       'audio/mp4; codecs="mp4a.40.2"').replace(/no/, ''))) 
      a.src = soundfile_ma; 
     else 
      a.src = soundfile_mp; 

     a.autoplay = true; 
     return; 
    } else { 
     alert("Time almost up"); 
    } 
} 

播放声音,做这样的事情:

playSound("/file/horse.wav", "/file/horse.mp3","/file/horse.m4a");