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

时间:2012-04-11 11:32:59

标签: javascript html audio notifications html5-audio

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

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

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

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

  1. 我应该使用哪种编解码器?
  2. 嵌入音频文件的最佳做法是什么? (<embed><object>对比Flash与<audio>

11 个答案:

答案 0 :(得分:88)

此解决方案适用于几乎所有浏览器(即使没有安装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>

浏览器支持

使用的代码

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

答案 1 :(得分:56)

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

var audio = new Audio('/path/to/audio/file.mp3');
audio.play();

查看更多here

答案 2 :(得分:14)

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

优点:

  • JavaScript-plugin,用于播放基于Web Audio API的声音,并回退到HTML5音频。
  • 插件适用于大多数流行的桌面和移动浏览器,可以在任何地方使用,从常见的网站到浏览器游戏。
  • 包括音频精灵支持。
  • 没有任何依赖(不需要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");

答案 3 :(得分:4)

雅虎的媒体播放器怎么样? 刚刚嵌入雅虎的图书馆

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

并像

一样使用它
<a id="beep" href="song.mp3">Play Song</a>

自动启动

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

答案 4 :(得分:3)

播放跨浏览器兼容的通知

正如@Tim Tisdall在this帖子中所提出的建议,请检查Howler.js插件。

像chrome这样的浏览器会在performance改进最小化或不活动时禁用javascript执行。但是,即使浏览器处于非活动状态或被用户最小化,这也会播放通知声音。

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

               sound.play();

希望帮助某人。

答案 5 :(得分:2)

使用audio.js作为<audio>标记的polyfill,并使用后备闪存。

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

答案 6 :(得分:1)

如果您想通过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()

答案 7 :(得分:0)

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

答案 8 :(得分:0)

我们可以像下面那样一起使用音频和对象:

# -*- coding:utf-8 -*-
# Time: 2018/7/16 19:38

from selenium import webdriver
from time import sleep
import time
from PIL import Image


def time_format():
    current_time = time.strftime('%Y%m%d%H%M%S',time.localtime(time.time()))
    return current_time

driver = webdriver.Chrome()
driver.get('http://www.baidu.com/')

driver.save_screenshot("full.png")

element = driver.find_element_by_id("su")
print(element.location)
print(element.size)

xPiont = element.location['x']
yPiont = element.location['y']

element_width = xPiont + element.size['width']
element_height = yPiont + element.size['height']

picture = Image.open('full.png')

picture = picture.crop((xPiont, yPiont, element_width,element_height))
print(picture.size)
picture.save(time_format() + ".png")

sleep(2)
driver.quit()

甚至为var audio = {}; audio['ubuntu'] = new Audio(); audio['ubuntu'].src="start.ogg"; audio['ubuntu'].play(); addEventListener添加play

答案 9 :(得分:0)

我写了一种干净的播放声音的实用方法:

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

答案 10 :(得分:0)

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

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

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

$('#playSoundBtn').trigger('click');
相关问题