情形一:浏览器未进行过声音文件的播放,直接最小化,然后触发去播放声音文件,声音文件无法播放。此时再将浏览器放大,触发播放声音文件的方法,声音正常播放。
情形二:浏览器最大化且进行过声音文件的播放,然后最小化,再去触发播放声音文件,可以正常播放。
代码如下
canplaythroughListener;
init(fileName: string) {
let fileUrl = '/' + fileName
this._source.setAttribute("src", fileUrl)
// 再次加载相同的音频文件--重载
this._audio.load()
this._audio.autoplay = true;
return new Promise((resolve, reject) => {
this.canplaythroughListener = () => {
console.log('this._audio.readyState', this._audio.readyState);
try {
if (this._audio.readyState == this._audio.HAVE_ENOUGH_DATA) {
this._audio.play()
.then(()=>{
this._audio.play()
console.log('this._audio', this._audio)
resolve(undefined)
})
.catch((err)=>{
if (err.name == 'NotAllowedError') {
console.log('NotAllowedError')
reject()
}
})
}
} catch (error) {
console.log('catch-error')
}
};
this._audio.addEventListener("canplaythrough", this.canplaythroughListener);
// test
this._audio.addEventListener('load', () => {
console.log('load~~~~')
this._audio.addEventListener('canplaythrough', function() {
console.log('Video can play through');
});
});
this._audio.addEventListener('error', function() {
console.log('Error loading video');
});
})
}
测试结果如下:当处于情形一的时候,audio对象的addEventListener事件未添加成功。当处于情形二的时候,addEventListener事件添加成功,内部方法也可正常执行。
猜测:声音只要正常播放过,全局即存在this._audio.addEventListener("canplaythrough"),后续哪怕浏览器最小化,也可以正常播放。
请问造成浏览器初始化状态未最小化且未进行过声音文件的播放,执行声音文件的播放方法且无法播放的原因是什么,有什么解决方案?