用 JavaScript 播放声音 [英] Playing sound with JavaScript

查看:30
本文介绍了用 JavaScript 播放声音的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Doesn't matter what I do, I simply can't get this to play a sound in Firefox or IE, or Chrome for that matter.

<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>

推荐答案

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

Try using this revised version of the function play()

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

您的代码的问题在于您使用了 src 属性,该属性用于 <embed>标签.相反,使用 <object> 的 data 属性.标签.



如果您想从中获得最大的兼容性,您还应该考虑添加 embed 标签作为 object 标签的替代品.它的工作方式是这样的:

The problem with your code was you were using the src attribute, which is for the <embed> tag. Instead, use the data attribute for the <object> tag.



If you are trying to get the most compatibility out of this, you should also consider adding the embed tag as an alternate for the object tag. The way it works is like this:

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

这类似于 noscript 标签,其中不支持 object 标签的旧浏览器求助于 embed 标签.

This works similar to the noscript tag, where older browsers that don't support the object tag resort to the embed tag.

这篇关于用 JavaScript 播放声音的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆