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

How to play a notification sound on websites?

本文关键字:播放 通知 声音 网站      更新时间:2023-09-26

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

打开

网站时,声音不应自动启动(立即)。相反,它应该通过JavaScript按需播放(当某个事件发生时)。

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

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

  1. 我应该使用什么编解码器?
  2. 嵌入音频文件的最佳做法是什么?( <embed><object> vs. 闪光灯 vs. <audio>

> 2023 解决方案

function playSound(url) {
  const audio = new Audio(url);
  audio.play();
}
<button onclick="playSound('https://your-file.mp3');">Play</button>  

浏览器支持

边缘 12+, 火狐 20+, IE浏览器 9+, 歌剧 15+, Safari 4+, 铬

编解码器支持

只需使用 MP3

<小时 />

旧解决方案

(适用于旧版浏览器)

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>';
}
<button onclick="playSound('bing');">Play</button>  
<div id="sound"></div>

浏览器支持

  • <audio>(现代浏览器)
  • <embed>(回退)

使用的代码

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

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

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

在此处查看更多内容。

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

  • 基本演示
  • 高级演示
  • Ion.Sound GitHub 页面

优势:

  • JavaScript插件,用于播放基于Web Audio API的声音,并回退到HTML5 Audio。
  • 插件适用于最流行的桌面和移动浏览器,可以在任何地方使用,从常见的网站到浏览器游戏。
  • 包括音频精灵支持。
  • 没有依赖关系(不需要jQuery)。
  • 包括25种免费声音。

设置插件:

// 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");

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

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

并像使用它一样使用

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

自动启动

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

播放跨浏览器兼容通知

根据这篇文章中@Tim Tisdall的建议,检查Howler.js插件。

像 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();

希望帮助某人。

如果你想通过JS自动化这个过程:

包括html中的某个地方:

<button onclick="playSound();" id="soundBtn">Play</button>  

并通过js隐藏它:

<script type="text/javascript">
document.getElementById('soundBtn').style.visibility='hidden';
function performSound(){
var soundButton = document.getElementById("soundBtn");
soundButton.click();
}
function playSound() {
      const audio = new Audio("alarm.mp3");
      audio.play();
    }
</script>

如果您想播放声音,只需在某个地方打电话performSound()

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

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

现在,您可以在播放声音时触发按钮

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

使用音频.js这是回退到闪存的<audio>标签的填充物。

通常,请查看 HTML 5 API 的填充 https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-Browser-Polyfills。(它包括更多<audio>填充物

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

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

我写了一个干净的函数式方法来播放声音:

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

我们可以同时使用音频和对象,如下所示:

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

甚至为playended添加addEventListener