如何在网站上播放通知声音? [英] How to play a notification sound on websites?

查看:50
本文介绍了如何在网站上播放通知声音?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

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

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

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

So, basically there are two questions:

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

    推荐答案

    2021 解决方案

    function playSound(url) {
      const audio = new Audio(url);
      audio.play();
    }
    

    <button onclick="playSound('https://your-file.mp3');">Play</button>  
    

    浏览器支持

    Edge 12+、Firefox 20+、Internet Explorer 9+、Opera 15+、Safari 4+、Chrome

    Browser support

    Edge 12+, Firefox 20+, Internet Explorer 9+, Opera 15+, Safari 4+, Chrome

    只需使用 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>
    

    浏览器支持