vue播放mp3实现

31 篇文章 0 订阅
10 篇文章 0 订阅

1.在main.js中注册全局vue:mp3vue

2.在app.vue引入组件:<mp3vue/>

3.在需要调用的地方调用组件方法:this.mp3vue.mp3play(1)

4.组件代码:

<template>
 <div class="listen">
 <!-- 语音播放功能 -->
 <div >

 <!-- <input type="button" id="tts_btn" @click="myplay(0)" value="播放"> -->
 </div>
 <div id="bdtts_div_id">
 <audio id="successpay" autoplay="autoplay">
 <source id="tts_source_id" src="../image/SuccessPay.mp3" type="audio/mpeg">
 </audio>
 <audio id="failpay" autoplay="autoplay">
 <source id="tts_source_id" src="../image/FailPay.mp3" type="audio/mpeg">
 </audio>
 </div>
 </div>
</template>

<script>
export default {
 name: 'myplaymp3',
 data () {
 return {

 }
 },
 methods: {
 myplay(action){
  console.log("#mp3pay")

switch (action){
  case 1:
  var ttsAudio = document.getElementById('successpay');
  ttsAudio.play();
    break;
  case 0:
    var ttsAudio = document.getElementById('failpay');
    ttsAudio.play();
      break;
  default:
    break;
}

 }
 }
}
</script>

<style>
.listen
    {
    position:fixed;
     right:10px;
     bottom:10px;
     // top:20px;
     z-index:9999;
    }
</style>
 

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
实现音乐播放,可以使用 HTML5 的 audio 标签,同时结合 Vue3 的响应式数据和生命周期函数来控制音乐的播放、暂停、进度等。 首先,在 Vue3 的 setup 函数中定义一个响应式数据,用于存储音乐的播放状态、当前播放时间和总时长: ``` import { ref } from 'vue' export default { setup() { const audio = ref(null) // audio 元素 const isPlaying = ref(false) // 播放状态 const currentTime = ref(0) // 当前播放时间 const duration = ref(0) // 总时长 // 监听 audio 元素的事件 const onAudioPlay = () => { isPlaying.value = true } const onAudioPause = () => { isPlaying.value = false } const onAudioTimeUpdate = () => { currentTime.value = audio.value.currentTime duration.value = audio.value.duration } return { audio, isPlaying, currentTime, duration, onAudioPlay, onAudioPause, onAudioTimeUpdate } } } ``` 然后,在模板中使用 audio 标签,并绑定相关事件和数据: ``` <template> <div> <audio ref="audio" @play="onAudioPlay" @pause="onAudioPause" @timeupdate="onAudioTimeUpdate"> <source src="music.mp3" type="audio/mpeg"> </audio> <button @click="isPlaying ? audio.pause() : audio.play()"> {{ isPlaying ? '暂停' : '播放' }} </button> <div> {{ currentTime }} / {{ duration }} </div> </div> </template> ``` 最后,在组件的 mounted 生命周期中获取 audio 元素,并调用 play 方法开始播放音乐: ``` import { ref, onMounted } from 'vue' export default { setup() { const audio = ref(null) // ... onMounted(() => { audio.value.play() }) return { audio, // ... } } } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

智慧方

开发程序不易

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值