Answers:
该解决方案几乎可以在所有浏览器上运行(即使未安装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>
从2016年开始,以下内容就足够了(您甚至不需要嵌入):
let src = 'https://file-examples.com/wp-content/uploads/2017/11/file_example_MP3_700KB.mp3';
let audio = new Audio(src);
audio.play();
在这里查看更多。
Uncaught (in promise) DOMException
另一个插件,用于在网站上播放通知声音:Ion.Sound
优点:
设置插件:
// 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(); });
display: none
了它,它将不再播放声音。此外,雅虎媒体库显示左链路的小“戏”图标..
visiblity: hidden;
您的答案
播放跨浏览器兼容的通知
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();
希望可以帮助某人。
sound.play()
首先如何运行?吼叫会将所有setTimeouts放在包装器中吗?
使用audio.js,它是<audio>
代码的polyfill,具有回退到 Flash的功能。
通常,请查看https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-Browser-Polyfills以获取HTML 5 API的polyfill。(其中包括更多的<audio>
polyfill)
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;
}