H5背景音乐自动播放(兼容微信IOS,进程后台切换自动停止播放,本文例子为Vue写法)

<template>
    <audio src="./static/music.mp3" id="bgMusic" preload="auto" loop></audio>
    <div class="bgMusicBtn" @click="bgMusicPlayOrPause('bgMusic')">
        <img :src="playFlag ? playImg : pauseImg" :class="{rotate: playFlag}">
    </div>
</template>
 
export default {
    data() {
        return {
            playFlag: true,
            playImg: require('../../static/play.png'),
            pauseImg: require('../../static/pause.png'),
            clickMusicBtn: false
        }
    },
    mounted() {
        this.audioAutoPlay('bgMusic');

        document.addEventListener("visibilitychange", (e) => { // 兼容ios微信手Q
            if (this.clickMusicBtn) { // 点击了关闭音乐按钮
                if (this.playFlag) {
                    this.audioAutoPlay('bgMusic');
                    this.playFlag = true;
                } else {
                    this.audioPause('bgMusic');
                    this.playFlag = false;
                }

                text.innerHTML = e.hidden;
                if (e.hidden) {  // 网页被挂起
                    this.audioAutoPlay('bgMusic');
                    this.playFlag = true;
                } else { // 网页被呼起
                    this.audioPause('bgMusic');
                    this.playFlag = false;
                }
            } else { // 未点击关闭音乐按钮
                if (this.playFlag) {
                    this.audioPause('bgMusic');
                    this.playFlag = false;
                } else {
                    this.audioAutoPlay('bgMusic');
                    this.playFlag = true;
                }

                text.innerHTML = e.hidden;
                if (e.hidden) {  // 网页被挂起
                    this.audioPause('bgMusic');
                    this.playFlag = false;
                } else { // 网页被呼起
                    this.audioAutoPlay('bgMusic');
                    this.playFlag = true;
                }
            }
        });
    },
methods: {
    bgMusicPlayOrPause(id) {
        this.clickMusicBtn = !this.clickMusicBtn;
        if (this.playFlag) {
            this.audioPause(id);
            this.playFlag = false;
        } else {
            this.audioAutoPlay(id);
            this.playFlag = true;
        }
    },
    audioPause(id) {
        var audio = document.getElementById(id);
        audio.pause();
        document.addEventListener("WeixinJSBridgeReady", function () {
            audio.pause();
        }, false);
        document.addEventListener('YixinJSBridgeReady', function () {
            audio.pause();
        }, false);
    },
    audioAutoPlay(id) {
        var audio = document.getElementById(id);
        audio.play();
        document.addEventListener("WeixinJSBridgeReady", function () {
            audio.play();
        }, false);
        document.addEventListener('YixinJSBridgeReady', function () {
            audio.play();
        }, false);
    }
 }
}
posted @ 2018-07-24 14:13  SKILL·NULL  阅读(3548)  评论(0编辑  收藏  举报