在浏览器(Chrome)中播放声音,来自 javascript

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18739888/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 13:02:26  来源:igfitidea点击:

Playing a sound in a browser (Chrome), from javascript

javascriptaudio

提问by user36956

I am writing an html page. I want it to make sounds, as specified by some javascript as it runs.

我正在写一个 html 页面。我希望它在运行时发出一些 javascript 指定的声音。

In the html, as recommended in the answers I have read here, I have the line

在 html 中,正如我在此处阅读的答案中所推荐的那样,我有一行

<embed src="wavs/beep.wav" autostart="true" width="0" height="0" id="beep" 
  enablejavascript="true">

This plays the sound at load time, so I am confident I have given a valid path to a valid .wav file. (I will set autostart to false once everything is working.)

这会在加载时播放声音,所以我相信我已经给出了一个有效的 .wav 文件的有效路径。(一旦一切正常,我会将自动启动设置为 false。)

I have a function

我有一个功能

function playSound ( soundname )   
  {
    var thissound = document.getElementById( soundname );
    thissound.Play();
    alert( "Played " + soundname );
  }

which I call using

我称之为使用

  playSound( "beep" );

But when that call is made, there is no sound, although the alert happens. It looks to me as if I am doing everything in the recommended way, but I must have got something wrong. What should I check next?

但是当发出那个呼叫时,虽然警报发生了,但没有声音。在我看来,好像我正在按照推荐的方式做所有事情,但我一定是出了什么问题。我接下来应该检查什么?

回答by IliasT

Use the native HTML5 Audio API

使用原生 HTML5 音频 API

In Chrome's console try creating a new instance of the Audio element, passing in the path of the sound you want to buffer. For example, if we want a typewriter sound we can do something like:

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

var typeWriter = new Audio("https://www.freesound.org/data/previews/256/256458_4772965-lq.mp3");

Note: for this exact sound to buffer and avoid a CSRF issue, you must be working in a console at www.freesound.org

注意:为了缓冲这个确切的声音并避免 CSRF 问题,您必须在 www.freesound.org 的控制台中工作

typeWriternow represents an html audio tag.

typeWriter现在代表一个 html 音频标签。

Try making the sound loop by setting typeWriter.loop = true

尝试通过设置使声音循环 typeWriter.loop = true

Finally, play/pause the sound with typeWriter.play()& typeWriter.pause()

最后,用typeWriter.play()&播放/暂停声音typeWriter.pause()

回答by Nosakhare Belvi

Have tried this code, and it works well in most browsers used the js method below

已经尝试过这段代码,它在大多数使用下面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;
    }
}

回答by Crusher

You are getting an error because the getElementById gives you an embed element and not an audio element. embed element does not know how to play. In other words, there is no play method in embed element. Use the following code to play it properly.

您收到一个错误,因为 getElementById 为您提供了一个嵌入元素而不是一个音频元素。嵌入元素不知道怎么玩。换句话说,嵌入元素中没有播放方法。使用以下代码可以正常播放。

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

One more note. Depending on the browsers you might want to support, you need multiple versions of the audio sources defined. Refer to thisfor details.

再一记。根据您可能想要支持的浏览器,您需要定义多个版本的音频源。请参阅了解详情。

回答by Joris Lindhout

Shouldn't it be .play() - with a lowercase 'p'?

不应该是 .play() - 带有小写的“p”吗?

Depending on what browsers you want to support, you might want to consider replacing your <embed>with an HTML5 <audio>tag: http://www.storiesinflight.com/html5/audio.html. This page has some working js examples as well!

根据您想要支持的浏览器,您可能需要考虑用<embed>HTML5<audio>标签替换您的:http: //www.storiesinflight.com/html5/audio.html。此页面也有一些有效的 js 示例!