移动端Web自动播放音乐问题

在这里插入图片描述

本文原地址

关于移动端Web音乐自动播放的问题,可以分为三种:

  1. 支持audio的autoplay,大部分安卓机子的自带浏览器和微信,大部分的IOS微信(无需特殊解决)
  2. 不支持audio的autoplay,部分的IOS微信 (解决ios下的微信打开的页面背景音乐无法自动播放)
  3. 不支持audio的autoplay,部分的安卓机子的自带浏览器(比如小米)和ios safari(只能做用户触屏时触发播放,本文介绍)

原因

  1. 微信的js api是建立在微信内置浏览器的私有对象WeixinJSBridge上,在微信中打开页面的话会初始化这个对象,当这个对象准备好的时候,会抛出WeixinJSBridgeReady这个事件,我们在这个事件的回调中可以播放音乐。
  2. 以前的IOS是支持音频自动播放的,但是在IOS4.2.1版本之后,苹果不支持自动播放,为了用户着想,禁止了autoplay和JS “onload” 加载播放,在此我们监听用户触屏时触发。更多资料见官方文档Safari Developer Library

User Control of Downloads Over Cellular Networks In Safari on iOS (for all devices, including iPad), where the user may be on a cellular network and be charged per data unit, preload and autoplay are disabled. No data is loaded until the user initiates it.

This means the JavaScript play() and load() methods are also inactiveuntil the user initiates playback, unless the play() or load() method is triggered by user action. In other words, a user-initiated Play button works, but an onLoad=“play()” event does not.

解决方案

<audio src="bg.mp3" id="CW" autoplay preload></audio>

jQuery(document).ready(function($) {
    audioAutoPlay('CW');
});

function audioAutoPlay(id){

    var audio = document.getElementById(id),
        play = function(){
            audio.play();
            document.removeEventListener("touchstart",play, false);
        };

    audio.play();
    
    //兼容微信
    document.addEventListener("WeixinJSBridgeReady", function () {
        play();
    }, false);

    //兼容易信
    document.addEventListener('YixinJSBridgeReady', function() {
        play();
    }, false);

    document.addEventListener("touchstart",play, false);
}

猜你喜欢

转载自blog.csdn.net/qq_34812257/article/details/84493798