Javascript 如何在网站上播放通知声音?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10105063/
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-08-23 23:51:28  来源:igfitidea点击:

How to play a notification sound on websites?

javascripthtmlaudionotificationshtml5-audio

提问by Timo

When a certain event occurs, I want my website to play a short notification sound to the user.

当某个事件发生时,我希望我的网站向用户播放简短的通知声音。

The sound should notauto-start (instantly) when the website is opened. Instead, it should be played on demand via JavaScript (when that certain event occurs).

声音应该自动启动(瞬间)的网站打开时。相反,它应该通过 JavaScript 按需播放(当特定事件发生时)。

It is important that this also works on older browsers (IE6 and such).

重要的是,这也适用于较旧的浏览器(IE6 等)。

So, basically there are two questions:

所以,基本上有两个问题:

  1. What codec should I use?
  2. What's best practice to embed the audio file? (<embed>vs. <object>vs. Flash vs. <audio>)
  1. 我应该使用什么编解码器?
  2. 嵌入音频文件的最佳做法是什么?( <embed>vs. <object>vs. Flash vs. <audio>)

采纳答案by Timo

This solution works on pretty much all browsers (even without Flash installed):

这个解决方案几乎适用于所有浏览器(即使没有安装 Flash):

<!doctype html>
<html>
  <head>
    <title>Audio test</title>
    <script>
      /**
        * Plays a sound using the HTML5 audio tag. Provide mp3 and ogg files for best browser support.
        * @param {string} filename The name of the file. Omit the ending!
        */
      function playSound(filename){
        var mp3Source = '<source src="' + filename + '.mp3" type="audio/mpeg">';
        var oggSource = '<source src="' + filename + '.ogg" type="audio/ogg">';
        var embedSource = '<embed hidden="true" autostart="true" loop="false" src="' + filename +'.mp3">';
        document.getElementById("sound").innerHTML='<audio autoplay="autoplay">' + mp3Source + oggSource + embedSource + '</audio>';
      }
    </script>
  </head>

  <body>
    <!-- Will try to play bing.mp3 or bing.ogg (depends on browser compatibility) -->
    <button onclick="playSound('bing');">Play</button>  
    <div id="sound"></div>
  </body>
</html>

Browser support

浏览器支持

Codes used

使用的代码

  • MP3 for Chrome, Safari and Internet Explorer.
  • OGG for Firefox and Opera.
  • 适用于 Chrome、Safari 和 Internet Explorer 的 MP3。
  • 适用于 Firefox 和 Opera 的 OGG。

回答by dchacke

As of 2016, the following will suffice (you don't even need to embed):

截至 2016 年,以下内容就足够了(您甚至不需要嵌入):

let src = 'https://file-examples.com/wp-content/uploads/2017/11/file_example_MP3_700KB.mp3';
let audio = new Audio(src);
audio.play();

See more here.

在此处查看更多信息

回答by Cassio Landim

One more plugin, to play notification sounds on websites: Ion.Sound

另一个插件,用于在网站上播放通知声音:Ion.Sound

Advantages:

好处:

  • JavaScript-plugin for playing sounds based on Web Audio API with fallback to HTML5 Audio.
  • Plugin is working on most popular desktop and mobile browsers and can be used everywhere, from common web sites to browser games.
  • Audio-sprites support included.
  • No dependecies (jQuery not required).
  • 25 free sounds included.
  • JavaScript 插件,用于播放基于 Web 音频 API 的声音,并回退到 HTML5 音频。
  • 插件适用于最流行的桌面和移动浏览器,可以在任何地方使用,从常见的网站到浏览器游戏。
  • 包括音频精灵支持。
  • 没有依赖项(不需要 jQuery)。
  • 包括 25 个免费声音。

Set up plugin:

设置插件:

// set up config
ion.sound({
    sounds: [
        {
            name: "my_cool_sound"
        },
        {
            name: "notify_sound",
            volume: 0.2
        },
        {
            name: "alert_sound",
            volume: 0.3,
            preload: false
        }
    ],
    volume: 0.5,
    path: "sounds/",
    preload: true
});

// And play sound!
ion.sound.play("my_cool_sound");

回答by Starx

How about the yahoo's media player Just embed yahoo's library

雅虎的媒体播放器怎么样 嵌入雅虎的库

<script type="text/javascript" src="http://mediaplayer.yahoo.com/js"></script> 

And use it like

并使用它

<a id="beep" href="song.mp3">Play Song</a>

To autostart

自动启动

$(function() { $("#beep").click(); });

回答by shaijut

Play cross browser compatible notifications

播放跨浏览器兼容通知

As adviced by @Tim Tisdall from thispost , Check Howler.jsPlugin.

正如@Tim Tisdall 从这篇文章中所建议的,检查Howler.js插件。

Browsers like chrome disables javascriptexecution when minimized or inactive for performanceimprovements. But This plays notification sounds even if browser is inactive or minimized by the user.

chrome 等浏览器javascript在最小化或不活动时禁用执行以提高性能。但是即使浏览器处于非活动状态或被用户最小化,这也会播放通知声音。

  var sound =new Howl({
                     src: ['../sounds/rings.mp3','../sounds/rings.wav','../sounds/rings.ogg',
                           '../sounds/rings.aiff'],
                     autoplay: true,
                     loop: true
                    });

               sound.play();

Hope helps someone.

希望能帮助某人。

回答by Gabriele Petrioli

Use the audio.jswhich is a polyfill for the <audio>tag with fallback to flash.

使用audio.js,它是<audio>带有回退到Flash的标签的polyfill

In general, look at https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-Browser-Polyfillsfor polyfills to the HTML 5 APIs.. (it includes more <audio>polyfills)

一般来说,请查看https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-Browser-Polyfills以获取 HTML 5 API 的polyfills..(它包括更多<audio>polyfills

回答by Sfwan Essam

if you want calling event on the code The best way to do that is to create trigger because the browser will not respond if the user is not on the page

如果你想在代码上调用事件最好的方法是创建触发器,因为如果用户不在页面上,浏览器将不会响应

<button type="button" style="display:none" id="playSoundBtn" onclick="playSound();"></button>

now you can trigger your button when you want to play sound

现在您可以在想要播放声音时触发您的按钮

$('#playSoundBtn').trigger('click');

回答by ramancha

var audio = new Audio('audio_file.mp3');

function post()
{
  var tval=document.getElementById("mess").value;   
  var inhtml=document.getElementById("chat_div");
  inhtml.innerHTML=inhtml.innerHTML+"<p class='me'>Me:-"+tval+"</p>";
  inhtml.innerHTML=inhtml.innerHTML+"<p class='demo'>Demo:-Hi! how are you</p>";
  audio.play();
}

this code is from talkerscode For complete tutorial visit http://talkerscode.com/webtricks/play-sound-on-notification-using-javascript-and-php.php

此代码来自talkerscode 完整教程请访问http://talkerscode.com/webtricks/play-sound-on-notification-using-javascript-and-php.php

回答by Mostafa

We can just use Audio and an object together like:

我们可以一起使用 Audio 和一个对象,例如:

var audio = {};
audio['ubuntu'] = new Audio();
audio['ubuntu'].src="start.ogg";
audio['ubuntu'].play();

and even adding addEventListenerfor playand ended

甚至加入addEventListenerplayended

回答by Hyman

I wrote a clean functional method of playing sounds:

我写了一个干净的播放声音的功能方法:

sounds = {
    test : new Audio('/assets/sounds/test.mp3')
};

sound_volume = 0.1;

function playSound(sound) {
    sounds[sound].volume = sound_volume;
    sounds[sound].play();
}
function stopSound(sound) {
    sounds[sound].pause();
}
function setVolume(sound, volume) {
    sounds[sound].volume = volume;
    sound_volume = volume;
}