前述:最近解決的一個疑難雜症,是關於audio自動播放與監聽audio加載完成在ios上的兼容性問題,其表現爲pc,安卓谷歌瀏覽器正常,ios微信,谷歌瀏覽器不正常。
需求:在音頻加載前放置一個全局loading,音頻加載完成後取消loading,並自動播放;項目爲vue前端項目,兼容pc,移動端。
解決方案1(失敗):
that.audioTimer=setTimeout(function(){
that.audioLoading = that.$loading({
lock: true,
text: '音頻加載中...',
spinner: 'el-icon-loading',
background: 'rgba(0, 0, 0, 0.7)'
});
},200);
//兼容谷歌瀏覽器
audioElement.addEventListener("progress", function() {
//關閉loading並讓audio.paly()
});
audioElement.addEventListener("canplay", function() {
//關閉loading並讓audio.paly()
});
//兼容微信瀏覽器
document.addEventListener("WeixinJSBridgeReady", function () {
alert("微信")
//關閉loading並讓audio.paly()
}, false)
問題在於addEventListener("canplay")與(“progress”)在ios微信瀏覽器不兼容,而在微信瀏覽器上類似上述的兼容微信瀏覽器代碼根本難以實現,並且兼容這些瀏覽器需要寫很多重複的代碼,複用性不高;
解決方案2(成功):
思路,用全局自定義方法get請求替換監聽音頻加載是否完成方案;
第一步,封裝axios get方法
import axios from 'axios'
import { Loading } from 'element-ui'
const get = function(path, callback){
//配置路徑
let fainalPath = path;
if(path.indexOf("http") < 0){
fainalPath = "http://" + Host + path;
}
//延時Loading
let getloadtimer = null;
let getloading = null;
getloadtimer = setTimeout(function(){
getloading = Loading.service({
lock: true,
text: '資源加載中...',
spinner: 'el-icon-loading',
background: 'rgba(0, 0, 0, 0.7)'
});
},200);
//網絡不穩定Loading
let setIntvar = null;
let setIntvarnum = 0;
let netLoading = null;
setIntvar = setInterval(function(){
if(setIntvarnum>=10){
if(getloading != null) {
getloading.close();
}
netLoading = Loading.service({
lock: true,
text: '網絡環境不穩定,請您刷新或者重新登錄...',
spinner: 'el-icon-loading',
background: 'rgba(0, 0, 0, 0.7)'
});
}else {
setIntvarnum += 1
}
},1000);
//網絡請求
axios.get(fainalPath
,{headers: {
'Content-Type':'application/json;charset=UTF-8',
'Accept':'application/json'
}})
.then(function (response) {
closeAll(getloadtimer,setIntvar,getloading,netLoading);
callback(response)
})
.catch(function (error) {
closeAll(getloadtimer,setIntvar,getloading,netLoading);
if (error.response) {
console.log(error.response.data);
console.log(error.response.status);
tipError(error.response.data.code,error.response.status,path)
}
})
};
<audio id="playButton" :src="audioSrc" :autoplay="autoplay" @ended="audioEnd"></audio>
第二步:在vue頁面中,監聽數據變幻,並加載音頻;
watch: {
'response': 'renderData'
}
response是父組件傳來的數據;renderData是子組件的數據初始化方法;在renderData裏做下面的方法。
let audioSrc = "http://xxxx.com/測試.mp3";
let audioElement = document.getElementById('playButton');
api.get(audioSrc,function(response){
//audioElement.load();
audioElement.play();
})
第三步:當你點擊音頻時不需要重複加載,它會從cache裏去拿;
choiceAudio (id) {
this.isEnded = 'pause';
let audioSrc = "http:/xxxx"+ id +".mp3";
document.getElementById('playButton').setAttribute('src', audioSrc);
document.getElementById('playButton').load();
document.getElementById('playButton').play();
},
總結:經過方案二,在pc,安卓,ios裏都能正常運行,完美!