多个语音 audio,播放互斥
<template>
<div class="soundWrap">
<div :key='item' v-for="(item, key) in vocabulary">
<audio class="audio" @error="onError" :key='item' :src="item.audio"></audio>
<div class="soundloading" v-if="soundloading">
<img src="../static/img/soundloading.png">
</div>
<div class="soundplay" v-else @click="startPlay(key, item.audio)" :class="(voice && index === key) ? 'voiceshow' : '' "></div>
</div>
</div>
</template>
<script type="text/javascript">
export default {
data () {
return {
soundloading: false,
voice: false,
index: null
}
},
methods: {
// 播放完当前才可播放下一个
startPlay (key, src) {
this.index = key
this.voice = true
if (!this.currentAudio) {
this.currentAudio = new Audio(src)
this.currentAudio.play()
this.voice = true
this.currentAudio.onended = () => {
this.currentAudio = null
this.voice = false
}
}
},
// 互斥播放
startPlay (key, src) {
let audio = document.querySelectorAll('audio')
for (var i = 0, len = audio.length; i < len; i++) {
audio[i].pause()
this.voice = false
audio[i].load()
}
audio[key].play()
this.voice = true
this.index = key
audio[key].onended = () => {
this.voice = false
}
},
onError () {
this.soundloading = true
},
// 缓存音频调用
onWaiting (res) {
console.log(res)
this.soundloading = true
}
}
}
</script>
<style scoped='scoped' lang="scss">
@keyframes play {
0% {
background: url(/static/img/sound1.png) no-repeat;
background-size: 100% 100%;
}
50% {
background: url(/static/img/sound2.png) no-repeat;
background-size: 100% 100%;
}
100% {
background: url(/static/img/sound3.png) no-repeat;
background-size: 100% 100%;
}
}
.voiceshow {
animation: play 2s infinite;
-webkit-animation: play 2s infinite;
}
</style>
注释:播放按钮之间操作互斥,例如点击播放第一个音频后,未播完情况下点击另一个音频,第一个音频的原音暂停,播放第二个音频的原音

浙公网安备 33010602011771号