用JavaScript播放声音

FaN*_*NIX 2 html javascript audio

无论我做什么,我根本无法让它在Firefox或IE或Chrome中播放声音.

<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>
Run Code Online (Sandbox Code Playgroud)

Kra*_*anu 6

尝试使用这个修改版本的函数play()

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);
}
Run Code Online (Sandbox Code Playgroud)

代码的问题在于您使用的是src属性,该属性用于<embed>标记.而是使用<object>标记的data属性.



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

<object data="test.wav" type="audio/wav" autostart="true">
<embed src="test.wav" autostart="true" alt="Could not load audio" />
</object>
Run Code Online (Sandbox Code Playgroud)

这类似于noscript标记,其中不支持object标记的旧浏览器使用embed标记.