多个语音 audio,播放互斥

本文详细介绍了一个基于Vue.js的音频播放组件实现过程,包括如何使用v-for循环遍历音频文件,实现音频的加载、播放及错误处理。文章还探讨了播放按钮之间的互斥操作,确保同一时间只有一个音频正在播放。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<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>

注释:播放按钮之间操作互斥,例如点击播放第一个音频后,未播完情况下点击另一个音频,第一个音频的原音暂停,播放第二个音频的原音

转载于:https://www.cnblogs.com/luov/p/10773166.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值