H5兼容安卓自动播放背景音乐

mounted() {
		
			const bgm = new this.BGMAutoPlayMgr('https://xxx/baobao-bg2.mp3');
			// bgm.toggleBGM();//打开、关闭播放,第一次自动播放不需要调用
			
		},
		methods: {
			BGMAutoPlayMgr(url) {
			    this.audioContext = new (window.AudioContext || window.webkitAudioContext || window.mozAudioContext)();
			    this.sourceNode = null;
			    this.buffer = null;
			    this.isPlayingBGM = false;
			    this.toggleBGM = function () {
			        if (typeof this.sourceNode == 'object') {
			            if (this.isPlayingBGM) {
			                this.sourceNode.stop();
			                this.isPlayingBGM = false;
			            } else this._playSourceNode();
			        }
			    }
			    this._playSourceNode = function () {
			        const audioContext = this.audioContext;
			        audioContext.resume();
			        const _sourceNode = audioContext.createBufferSource();
			        _sourceNode.buffer = this.buffer;
			        _sourceNode.loop = true;
			        _sourceNode.connect(audioContext.destination);
			        _sourceNode.start(0);
			        this.sourceNode = _sourceNode;
			        this.isPlayingBGM = true;
			    }
			    let loadAndAutoPlay = (audioUrl) => {
			        const audioContext = this.audioContext;
			        const xhr = new XMLHttpRequest();
			        xhr.open('GET', audioUrl, true);
			        xhr.responseType = 'arraybuffer';
			        xhr.onreadystatechange = () => {
			            if (xhr.status < 400 && xhr.status >= 200 && xhr.readyState === 4) {
			                audioContext.decodeAudioData(xhr.response, buffer => {
			                    this.buffer = buffer;
			                    WeixinJSBridge.invoke("getNetworkType", {}, () => this._playSourceNode());
			                });
			            }
			        }
			        xhr.send();
			    }
			    loadAndAutoPlay(url);
			    loadAndAutoPlay = null;
			},
}

猜你喜欢

转载自blog.csdn.net/qq_35713752/article/details/131423392