移動端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);
}
相關文章
相關標籤/搜索