解决方案#1
我的解决方案是创建一个iframe
<iframe src="audio/source.mp3" allow="autoplay" style="display:none" id="iframeAudio">
</iframe>
and audio
标签也适用于非 Chrome 浏览器
<audio autoplay loop id="playAudio">
<source src="audio/source.mp3">
</audio>
并在我的script
var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);
if (!isChrome){
$('#iframeAudio').remove()
}
else {
$('#playAudio').remove() // just to make sure that it will not have 2x audio in the background
}
解决方案#2:
根据 @Leonard 的说法,还有另一种解决方法
创建一个iframe
它不会播放任何内容,只是为了在第一次加载时触发自动播放。
<iframe src="silence.mp3" allow="autoplay" id="audio" style="display: none"></iframe>
mp3 文件的良好来源沉默.mp3
然后轻松播放您的真实音频文件。
<audio id="player" autoplay loop>
<source src="audio/source.mp3" type="audio/mp3">
</audio>
我个人更喜欢解决方案#2因为它是一种更干净的方法,不需要过多依赖 JavaScript。
2019 年 8 月更新
解决方案#3
作为替代方案,我们可以使用<embed>
For Firefox看来音频自动播放正在工作,所以我们不需要<embed>
元素,因为它将创建双音频运行。
// index.js
let audioPlaying = true,
backgroundAudio, browser;
browser = navigator.userAgent.toLowerCase();
$('<audio class="audio1" src="audio.mp3" loop></audio>').prependTo('body');
if (!browser.indexOf('firefox') > -1) {
$('<embed id="background-audio" src="audio.mp3" autostart="1"></embed>').prependTo('body');
backgroundAudio = setInterval(function() {
$("#background-audio").remove();
$('<embed id="background-audio" src="audio.mp3"></embed>').prependTo('body');
}, 120000); // 120000 is the duration of your audio which in this case 2 mins.
}
另外,如果您的音频有切换事件,请确保删除创建的<embed>
音频元素。
Note:切换后,它将从头开始,因为<embed>
已经被删除并且<audio>
元素现在将正常播放。
$(".toggle-audio").on('click', function(event) {
audioPlaying = !audioPlaying;
$("#background-audio").remove();
clearInterval(backgroundAudio);
if (audioPlaying){
$(".audio1").play();
// play audio
}
else {
$(".audio1").pause();
}
现在确保隐藏这些<audio>
and <embed>
元素
audio, embed {
position: absolute;
z-index: -9999;
}
Note: diplay: none
and visibility: hidden
将使<embed>
元素不起作用。