- 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:Monitoring Weixinjsbridgeready event, domcontentloaded event JS API built in the shell browser built-in JS object Weixinjsbridge, Weixinjsbridge is not webview a open on it, 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 with gesture events (1) listen to the body's Touchstart event and play the music in the callback;Disadvantages:Some elements of the touch event may prevent bubbling, you need to adjust the play music function in the corresponding place (2) can increase the transparency layer, click on the transparent layer, play music, close the transparent layer;Disadvantages:The first click on the button element may not respond, causing damage to the user experience.
- Some apps do not support WebView music autoplay
Solution: 1. Shell browser support; 2. Play Music through 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