How to solve the problem that audio elements and video elements cannot be played automatically in ios and andriod

Reason: Because all major browsers are optimized to save traffic, automatic playback is not allowed when the user has no action (interaction);

//音频,写法一
<audio src="music/bg.mp3" autoplay loop controls>你的浏览器还不支持哦</audio>

//音频,写法二
<audio controls="controls"> 
    <source src="music/bg.ogg" type="audio/ogg"></source>
    <source src="music/bg.mp3" type="audio/mpeg"></source>
    优先播放音乐bg.ogg,不支持在播放bg.mp3
</audio>

//JS绑定自动播放(操作window时,播放音乐)
$(window).one('touchstart', function(){
    music.play();
})

//微信下兼容处理
document.addEventListener("WeixinJSBridgeReady", function () {
    music.play();
}, false);

//小结
//1.audio元素的autoplay属性在IOS及Android上无法使用,在PC端正常;
//2.audio元素没有设置controls时,在IOS及Android会占据空间大小,而在PC端Chrome是不会占据任何空间;
//3.注意不要遗漏微信的兼容处理需要引用微信JS;

Front-end training

Guess you like

Origin blog.csdn.net/msjhw_com/article/details/109044051