Skip to main content

Adding Background Music to WeChat Public Platform

Free2015-09-02#Solution#微信公众平台添加背景音乐#微信自动播放音乐#微信播放音频

Automatically play music when entering the page, no need to manually click, this article details the implementation method

1. Problem Restatement

Some public account messages can automatically play music after clicking in, without requiring users to manually trigger play, how is this achieved?

2. Solution Attempts

1. Audio Set autoplay Attribute to Play

Set autoplay="autoplay" on audio tag

Result: Can autoplay on some Android devices, IOS does not support

2. setTimeout Play

Delay execution of audio.play() after entering page

Result: Safari, IOS WeChat does not support

3. Button Play

Trigger play through clicking button or touch event

Result: Some Android WeChat does not support

4. Use Old WeChat API Callback to Play

Play through callback of network status acquisition API (whether success or failure, execute play)

var audio = document.getElementById('audio');

if (window.WeixinJSBridge) {
    WeixinJSBridge.invoke('getNetworkType', {}, function(e) {
        audio.play();
    }, false);
}else{
    document.addEventListener("WeixinJSBridgeReady", function() {
        WeixinJSBridge.invoke('getNetworkType', {}, function(e) {
            audio.play();
        });
    }, false);
}

Result: IOS WeChat does not support, Safari does not support (no compatibility handling done)

5. Use New WeChat API Callback to Play

Principle same as above, just used new WeChat API, for detailed information please see WeChat JS-SDK Documentation

var audio = document.getElementById('audio');

if (window.WeixinJSBridge) {
    wx.getNetworkType({
        success: function (res) {
            audio.play();
        },
        fail: function (res) {
            audio.play();
        }
    });
}else{
    document.addEventListener("WeixinJSBridgeReady", function() {
        wx.getNetworkType({
            success: function (res) {
                audio.play();
            },
            fail: function (res) {
                audio.play();
            }
        });
    }, false);
}

Result: IOS support unknown

6. WeChat API Callback Use AudioAPI to Play

AudioAPI cannot break IOS system's restriction on not allowing automatic audio download (see below for details), so tried using AudioAPI to play audio in callback

Note: Low version IOS does not support AudioAPI, Android support unknown

// Get AudioContext
window.context = getAudiocontext();
// Get audio data
window.source = null;
window.bufs = [];

// Execute
getBufs();


/**
 * Get AudioContext
 * @return {AudioContext} audio element related environment object
 */
function getAudiocontext() {
    window.AudioContext = (window.AudioContext || window.webkitAudioContext);
    if(window.AudioContext) {
        return new window.AudioContext();
    } else {
        console.log('not support web audio api');
    }
}

/**
 * Play
 * @param {Integer} 1: multiple sources directly connect to output device 2: multiple sources connect to output device through GainNode
 * @return nth
 */
function getBufs() {
    var audioURL = 'didi.mp3'; // Replace with audio file URL here
    var xhr1 = new XMLHttpRequest();

    xhr1.open('GET', audioURL, true);
    xhr1.responseType = 'arraybuffer'; // New thing in XMLHttpRequest 2
    xhr1.onload = function() {
        // Audio data is in xhr.response, not xhr.requestText
        bufs.push(xhr1.response);
    }
    xhr1.send();
}

//////////
// WeChat callback //
//////////

var audio = document.getElementById('audio');

function runNow() {
    context.decodeAudioData(bufs[0], function(buffer) {
        source = context.createBufferSource();
        source.buffer = buffer;
        // Source directly connects to output device
        source.connect(context.destination);
        source.start(0);
    });
}

if (window.WeixinJSBridge) {
    WeixinJSBridge.invoke('getNetworkType', {}, function(e) {
        setTimeout(runNow, 3000);
    }, false);
}else{
    document.addEventListener("WeixinJSBridgeReady", function() {
        WeixinJSBridge.invoke('getNetworkType', {}, function(e) {
            setTimeout(runNow, 3000);
        });
    }, false);
}

Result: iPhone5 does not support, 6p unknown, can trigger callback, but play code is invalid

7. Other Possibly Implementable Methods

  • Simulate event trigger (trigger)

Manually trigger event, play audio in event handler, not yet tested

  • New API

Officially published 1.0.0 version API does not support playing audio (only supports playing recordings), may open more audio APIs in the future, of course, that's for later

3. Solution

No perfectly compatible solution, after testing, iPhone 5S and 6 can use JS API callback method to play, Android autoplay is relatively easy, but some deeply customized models still cannot play

The difficulty of autoplay mainly comes from IOS, because IOS system restricts automatic download of audio and video, must be triggered by user action to play:

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 inactive until 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.

(From Safari HTML5 Audio and Video Guide)

For more solutions about IOS autoplay audio, please see Autoplay audio files on an iPad with HTML5

Also saw a solution:

if ("wView" in window) {
    window.wView.allowsInlineMediaPlayback = "YES";
    window.wView.mediaPlaybackRequiresUserAction = "NO";
}

Said that after adding above code, directly preload, autoplay is okay

Note: Not tested, effect unknown

4. DEMO

http://www.ayqy.net/t/autoplay.html

References

Comments

No comments yet. Be the first to share your thoughts.

Leave a comment