- Scenarios:, browsers, apps
- General solution: Use the AutoPlay attribute of the audio tag
- Phenomenon:
- Most iOS systems and few Android do not support AutoPlay
$ solution: The JS API for monitoring Weixinjsbridgeready events and domcontentloaded events is built on the built-in JS object Weixinjsbridge of the Shell browser, Weixinjsbridge is not webview open, the client needs to initialize the object, and when the object is ready, the client throws the event "Weixinjsbridgeready". Discover some models, monitor domcontentloaded and load events, and play music in callbacks, so for the sake of insurance, you can monitor two events at the same time to enhance their applicability. The code is as follows: <audio style= "Display:none; height:0 "id=" Bg-music "preload=" Auto "src=" ... /static/videos/bg-music.mp3 "loop=" Loop ></audio>
Document.addeventlistener (' domcontentloaded ', function () {
function Audioautoplay () {
var audio = document.getElementById (' Bg-music ');
Audio.play ();
Document.addeventlistener ("Weixinjsbridgeready", function () {
Audio.play ();
}, False);
}
Audioautoplay ();
});
- Auto Play is not supported in some Android browsers and all iOS under Safari
Solution: Play Music via gesture events (1) listen to the body's Touchstart event, play the music in the callback; disadvantage: The touch event of some elements may prevent bubbling, need to adjust the play music function in the corresponding place (2) can increase the transparency layer, click to transparent layer, play music, close transparent layer; Disadvantage: the first click on the button element may not respond, resulting in user experience damage.
- Some apps do not support WebView music autoplay
Solution: 1. Shell browser support; 2. Play music with gesture events full code://Music Playback
function Autoplaymusic () {
Automatically play music effects, solve browser or app auto-play problem
function Musicinbrowserhandler () {
Musicplay (TRUE);
Document.body.removeEventListener (' Touchstart ', musicinbrowserhandler);
}
Document.body.addEventListener (' Touchstart ', musicinbrowserhandler);
Automatically play music effects to solve autoplay problems
function Musicinweixinhandler () {
Musicplay (TRUE);
Document.addeventlistener ("Weixinjsbridgeready", function () {
Musicplay (TRUE);
}, False);
Document.removeeventlistener (' domcontentloaded ', musicinweixinhandler);
}
Document.addeventlistener (' domcontentloaded ', musicinweixinhandler);
}
function Musicplay (isplay) {
var media = document.queryselector (' #bg-music ');
if (isplay && media.paused) {
Media.play ();
}
if (!isplay &&!media.paused) {
Media.pause ();
}
}
A solution to solve the H5 page background music can not be automatically played