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

随着时间之神的音乐起舞

1、关于移动端Web音乐自动播放的问题,能够分为三种:

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

2、缘由

  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.html

3、解决方案

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

$(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);
}
相关文章
相关标签/搜索