import { Howl } from "howler";
const audioUtil = {
audioArr: [],
soundControl: {},
currentAudioId: "",
currentAudioIconDom: "",
isPageHide: false,
init(audioArr = []) {
this.audioArr = audioArr;
audioArr.forEach((item) => {
const { id, url, dom } = item;
if (!id || !url) return;
this.soundControl[id] = new Howl({
src: url.replace('http://', 'https://'),
preload: true,
loop: false,
autoplay: false,
html5: true,
volume: 1
});
this.soundControl[id].on('play', () => {
this.singleAudioIconPlay(dom);
});
this.soundControl[id].on('end', () => {
this.allAudioIconPause();
});
});
document.addEventListener('visibilitychange', this.handleVisibilityChange.bind(this));
console.log('audioUtil - init', new Date().getTime(), this.soundControl);
},
playOrPauseAudio(audioId) {
if (!audioId) return;
const audioInfo = this.audioArr.filter((item) => item.id === audioId)[0];
if (!audioInfo) return;
const { dom: audioIconDom } = audioInfo;
if (audioId === this.currentAudioId && this.soundControl[audioId]) {
if (this.soundControl[audioId].playing()) {
this.soundControl[audioId].pause();
this.allAudioIconPause();
} else {
this.soundControl[audioId].play();
this.singleAudioIconPlay(audioIconDom);
}
return;
}
this.pauseAudio();
if (!this.soundControl[audioId]) return;
this.soundControl[audioId].stop();
this.soundControl[audioId].play();
this.singleAudioIconPlay(audioIconDom);
this.currentAudioId = audioId;
this.currentAudioIconDom = audioIconDom;
},
pauseAudio() {
if (this.soundControl[this.currentAudioId]) {
this.soundControl[this.currentAudioId].pause();
this.allAudioIconPause();
}
},
allAudioIconPause() {
const doms = document.querySelectorAll(".audio-status-icon");
[...doms].forEach((item) => {
item.setAttribute("class", "audio-status-icon play");
});
},
singleAudioIconPlay(dom) {
if (!dom) return;
dom.setAttribute("class", "audio-status-icon pause");
},
handleVisibilityChange() {
if (window.document.hidden) {
if (
this.soundControl
&& this.soundControl[this.currentAudioId]
&& this.soundControl[this.currentAudioId].playing()
) {
this.isPageHide = true;
this.soundControl[this.currentAudioId].pause();
this.allAudioIconPause();
}
}
if (!window.document.hidden) {
if (
this.isPageHide
&& this.soundControl
&& this.soundControl[this.currentAudioId]
) {
this.isPageHide = false;
this.soundControl[this.currentAudioId].play();
this.singleAudioIconPlay(this.currentAudioIconDom);
}
}
},
destroy() {
document.removeEventListener('visibilitychange', this.handleVisibilityChange.bind(this));
if (this.soundControl) {
this.soundControl = null;
}
},
};
export default audioUtil;
import audioUtil from 'audio-util';
<div
class="audio-status-icon play"
ref="audioId"
@click.stop="playCurrentAudio(audioId)"
></div>
.audio-status-icon {
&.play {}
&.pause {}
}
audioUtil.init([{
id: 'audio1',
url: '',
dom: this.$refs['audio1'] || null
}, {
id: 'audio2',
url: '',
dom: this.$refs['audio2'] || null
}]);
playCurrentAudio(audioId) {
audioUtil.playOrPauseAudio(audioId);
}
audioUtil.destroy();