uni-app 添加背景音乐

首页

        
        data() {
            return {
                isPlay: false
            }
        },
        onLoad() {
            this.innerAudioContext = uni.createInnerAudioContext();
            this.playVoice('music.mp3')
            uni.$on('changePlay', isPlay => {
                this.playVoice(this.lastRecord, this.isPlay)
            })
        },
        methods: {
            playVoice(url, isPlay) { // url即为音频路径
                if (url) {
                    this.lastRecord = url; // 将路径赋值给定义的变量好做判断
                    this.innerAudioContext.src = url; // 配置音频播放路径
                    this.innerAudioContext.play(); // 播放
                    this.innerAudioContext.loop = true; // 是否循环播放
                }
                this.isPlay = !this.isPlay;
                if (isPlay) {
                    this.innerAudioContext.pause(); // 停止
                }
            }
        }

其他页面也想控制这个音乐按钮
我看app.vue不支持写template ,所以就每个页面都写了一下这个按钮,然后通过emit,on来传递数据


playVoice() {
                uni.$emit('changePlay', 1);
            },

没去写看公共的方法,就酱吧,我累了...

你可能感兴趣的:(uni-app 添加背景音乐)