从javascript在浏览器(Chrome)中播放声音

从javascript在浏览器(Chrome)中播放声音,javascript,audio,Javascript,Audio,我正在写一个html页面。我想让它发出声音,就像一些javascript在运行时指定的那样 在html中,正如我在这里阅读的答案中推荐的那样,我有一行 <embed src="wavs/beep.wav" autostart="true" width="0" height="0" id="beep" enablejavascript="true"> 我称之为使用 playSound( "beep" ); 但是,当发出警报时,没有声音,尽管警报发生了。在我看来,好像我在以

我正在写一个html页面。我想让它发出声音,就像一些javascript在运行时指定的那样

在html中,正如我在这里阅读的答案中推荐的那样,我有一行

<embed src="wavs/beep.wav" autostart="true" width="0" height="0" id="beep" 
  enablejavascript="true">
我称之为使用

  playSound( "beep" );
但是,当发出警报时,没有声音,尽管警报发生了。在我看来,好像我在以推荐的方式做每件事,但我一定是做错了什么。接下来我应该检查什么?

应该是吗.play()-带小写字母“p”


根据您希望支持的浏览器,您可能需要考虑用HTML5<代码>替换<代码> <代码>。这个页面也有一些js示例

由于getElementById提供的是嵌入元素而不是音频元素,因此出现错误。嵌入元素不知道如何播放。换句话说,在嵌入元素中没有play方法。使用以下代码正确播放

<html>
<script>
function playSound ( soundname )
  {
    var thissound = document.getElementById( soundname );
    thissound.play();
    alert( "Played " + soundname );
  }
</script>
<body>
  <audio src="wavs/beep.wav" id="beep" autostart="false"></audio>
  <input type=button onclick="playSound('beep')">play</input>
  </body>
  </html>

功能播放声音(声音名称)
{
var thissound=document.getElementById(soundname);
这个声音。play();
警报(“已播放”+声音名称);
}

详细信息。

您已经尝试过这段代码,并且它在大多数浏览器中都运行良好 使用下面的js方法

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

使用本机HTML5音频API

在Chrome的控制台中,尝试创建音频元素的新实例,传递要缓冲的声音路径。例如,如果我们想要打字机的声音,我们可以这样做:

var typeWriter = new Audio("https://www.freesound.org/data/previews/256/256458_4772965-lq.mp3"); var打字机=新音频(“https://www.freesound.org/data/previews/256/256458_4772965-lq.mp3"); 注意:为了缓冲和避免CSRF问题,您必须在www.freesound.org的控制台中工作

打字机
现在表示html音频标记

通过设置
typeWriter.loop=true


最后,用
typeWriter.play()
&
typeWriter.pause()

播放/暂停声音。谢谢,你说得对。Play()什么也不做,我得到警报但没有声音。play()实际上失败了,所以我没有收到警报。请参阅下面的Crushers评论:当您使用audio元素时,js应该可以工作! var typeWriter = new Audio("https://www.freesound.org/data/previews/256/256458_4772965-lq.mp3");