前言
用vue 做音乐播放的时候,在本地可以打开播放,但在微信里面不能播放音乐
所以这样解决
// 音乐播放 audioPlay(){ let _this = this; var audio = _this.music; if(_this.bgmUrl){ audio.src = _this.bgmUrl; //audio.play(); _this.esPlayMusic(); _this.timeupdate(); wx.ready(()=>{ }) typeof WeixinJSBridge !== 'undefined' && WeixinJSBridge.invoke('getNetworkType', {}, function (res) { //audio.play(); _this.esPlayMusic(); _this.timeupdate(); }); } }, timeupdate() { let _this = this; var audio = _this.music; audio.addEventListener("timeupdate", function() { var duration = this.duration; var currentTime = this.currentTime; var percentage = (currentTime / duration) * 100; if (percentage == 100) { _this.audioPlay(); typeof WeixinJSBridge !== 'undefined' && WeixinJSBridge.invoke('getNetworkType', {}, function (res) { _this.audioPlay(); }); } }) },
主要是这段代码
typeof WeixinJSBridge !== 'undefined' && WeixinJSBridge.invoke('getNetworkType', {}, function (res) { //audio.play(); _this.esPlayMusic(); _this.timeupdate(); });
后来又因为 点击过快 出现报错了
The play() request was interrupted by a call to pause()
因为上一个用户的播报还没结束,这一个播报就要覆盖上来了,所以需要异步处理下
上代码了
// 异步加载音乐播放 esPlayMusic(){ let _this = this; //let audio = document.getElementById("audioPlay"); var audio = _this.music; //audio.play(); var playPromise = audio.play(); if (playPromise) { playPromise.then(() => { // 音频加载成功 // 音频的播放需要耗时 setTimeout(() => { // 后续操作 //console.log("done"); }, audio.duration * 1000); // audio.duration 为音频的时长单位为秒 }).catch((e) => { //console.log("Operation is too fast, audio play fails"); }); } },
这样就解决了