P粉7383463802023-08-21 10:33:30
Solution #1
My solution was to create an iframe
<iframe src="audio/source.mp3" allow="autoplay" style="display:none" id="iframeAudio"> </iframe>
and audio
tags for non-Chrome browsers
<audio autoplay loop id="playAudio"> <source src="audio/source.mp3"> </audio>
and in my script
var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor); if (!isChrome){ $('#iframeAudio').remove() } else { $('#playAudio').remove() // 为了确保背景中不会有两个音频 }
Solution #2:
According to @Leonard, there is another solution
Create an iframe
that doesn't play anything, just to trigger autoplay on first load.
<iframe src="silence.mp3" allow="autoplay" id="audio" style="display: none"></iframe>
Good mp3 file source: silence.mp3
Then play your real audio files easily.
<audio id="player" autoplay loop> <source src="audio/source.mp3" type="audio/mp3"> </audio>
Personally prefer Solution #2 as it is a cleaner approach and less dependent on JavaScript.
Updated in August 2019
Solution #3
As an alternative we can use <embed>
ForFirefox
It seems audio autoplay is working so we don't need the <embed>
element as it will create two audios running at the same time.
// 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是你的音频持续时间,本例中为2分钟。 }
If your audio has a toggle event, make sure to delete the <embed>
element you created.
NOTE: After the switch it will start from the beginning since <embed>
has been removed and the <audio>
element will now play normally .
$(".toggle-audio").on('click', function(event) { audioPlaying = !audioPlaying; $("#background-audio").remove(); clearInterval(backgroundAudio); if (audioPlaying){ $(".audio1").play(); // 播放音频 } else { $(".audio1").pause(); }
Now make sure to hide these <audio>
and <embed>
elements
audio, embed { position: absolute; z-index: -9999; }
Note: diplay: none
and visibility: hidden
will make the <embed>
element not work.