본문으로 건너뛰기

위챗 공중플랫폼에 배경음악 추가

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

페이지 진입 시 자동으로 음악을 재생하며, 수동으로 클릭할 필요가 없습니다. 본고에서는 그 구현 방법을 자세히 소개합니다

一.문제 재술

어떤 공중계정 메시지를 클릭 진입한 후 자동으로 음악을 재생할 수 있으며, 사용자가 수동으로 트리거하여 play 할 필요가 없습니다. 이는 어떻게 구현되는 것일까요?

二.方案 시험

###1.audio 에 autoplay 속성 설정하여 재생

audio 태그에 autoplay="autoplay" 설정

결과: 일부의Android 기기에서는 자동 재생 가능, IOS 는 지원하지 않음

###2.setTimeout 으로 재생

페이지 진입 후 지연 실행 audio.play()

결과: Safari, IOS 위챗은 지원하지 않음

###3.버튼으로 재생

버튼 클릭 또는 touch 이벤트를 통해 재생 트리거

결과: 일부 Android 위챗은 지원하지 않음

###4.구 위챗 API 콜백으로 재생

네트워크 상태를 가져오는 인터페이스 콜백으로 재생 (성공 실패와 관계없이, 모두 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);
}

결과: IOS 위챗은 지원하지 않음, Safari 는 지원하지 않음 (호환성 처리를 하지 않음)

###5.신 위챗 API 콜백으로 재생

원리는 상동, 새로운 위챗 API 를 사용했을 뿐입니다. 상세 정보는 위챗 JS-SDK 설명문서 참조

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);
}

결과: IOS 의 지원성은 불명

###6.위챗 API 콜백에서 AudioAPI 를 사용하여 재생

AudioAPI 는 IOS 시스템이 자동으로 오디오를 다운로드할 수 없는 제한을 깨뜨릴 수 없습니다 (상세는 후문 참조). 따라서 콜백 내에서 AudioAPI 를 사용하여 오디오를 재생하는 것을 시도했습니다

주의: 저버전 IOS 는 AudioAPI 를 지원하지 않음, Android 의 지원성은 불명

// 获取 AudioContext
window.context = getAudiocontext();
// 获取音频数据
window.source = null;
window.bufs = [];

// 执行
getBufs();


/**
 * 获取 AudioContext
 * @return {AudioContext} andio 元素相关的环境对象
 */
function getAudiocontext() {
    window.AudioContext = (window.AudioContext || window.webkitAudioContext);
    if(window.AudioContext) {
        return new window.AudioContext();
    } else {
        console.log('not support web audio api');
    }
}

/**
 * 播放
 * @param {Integer} 1: 多个 source 直接连接输出设备 2: 多个 source 通过 GainNode 再连接输出设备
 * @return nth
 */
function getBufs() {
    var audioURL = 'didi.mp3'; // 这里替换为音频文件 URL
    var xhr1 = new XMLHttpRequest();

    xhr1.open('GET', audioURL, true);
    xhr1.responseType = 'arraybuffer'; // XMLHttpRequest 2 的新东西
    xhr1.onload = function() {
        // 音频数据在 xhr.response 中,而不是 xhr.requestText
        bufs.push(xhr1.response);
    }
    xhr1.send();
}

//////////
// 微信回调 //
//////////

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

function runNow() {
    context.decodeAudioData(bufs[0], function(buffer) {
        source = context.createBufferSource();
        source.buffer = buffer;
        // 源直接连接到输出设备
        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);
}

결과: iPhnoe5 는 지원하지 않음, 6p 는 불명, 콜백을 트리거할 수 있지만, play 코드는 무효

###7.기타 구현 가능한 방법

  • 이벤트 트리거 시뮬레이션 (trigger)

수동으로 이벤트를 트리거하고, 이벤트 핸들러 내에서 오디오를 재생. 미테스트

  • 신 API

공식 공개의 1.0.0 버전 API 는 오디오 재생을 지원하지 않음 (녹음 재생만 지원). 후속으로 더 많은 오디오 API 가 개방될 가능성이 있습니다. 물론, 그것은 후의 이야기

三.해결책

완벽하게 호환되는 해결책은 없습니다. 테스트에 따르면, iPhone 5S 및 6 에서는 JS API 콜백 방식으로 재생 가능, Android 의 자동 재생은 비교적 쉽지만, 일부 심도 커스터마이즈 기종에서는 여전히 재생할 수 없습니다

자동 재생의难点는 주로 IOS 에서 옵니다. IOS 시스템의 제한으로 인해 자동으로 오디오비디오를 다운로드할 수 없으며, 사용자 액션으로 재생을 트리거해야 합니다:

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.

(Safari HTML5 Audio and Video Guide 에서 인용)

IOS 자동 재생 오디오의 더 많은 해결책에 대해서는, Autoplay audio files on an iPad with HTML5 참조

또 다른 해결책도 보았습니다:

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

위 코드를 추가한 후, 직접 preload, autoplay 하면 된다고据说

주의: 미테스트, 효과는 불명

四.DEMO

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

참고 자료

댓글

아직 댓글이 없습니다

댓글 작성