vue3+ts 实现图标控制音乐播放

vue3+ts 实现图标控制音乐播放

前言: 最近负责一个展示型项目 需要背景音乐 且 可以控制播放

效果图

在这里插入图片描述

代码

<template>
	<div class="img-box">
		<img
			ref="imgRef"
			:class="{ rotate: playStatus }"
			src="https://storage.beta.custouch.com/res/8082/stopMusic.png"
			alt="music"
			@click="controlMusic"
		/>
		<audio ref="audioRef" :src="musicUrl" loop @play="onPlay"></audio>
	</div>
</template>
<script lang="ts">
	import { ref } from 'vue'
	export default {
		name: 'Music',
		setup() {
			const audioRef = ref<null|HTMLAudioElement>(null)
			const imgRef = ref<null|HTMLImageElement>(null)
			let playStatus = ref(false)
			const musicImg = ref({
				play: 'https://storage.beta.custouch.com/res/8080/music.png',
				pause: 'https://storage.beta.custouch.com/res/8082/stopMusic.png'
			})
			const musicUrl = 'https://storage.beta.custouch.com/res/audios/38/bgmusic.mp3'
			const controlMusic = () => {
				if (audioRef.value && imgRef.value) {
					if (playStatus.value) {
						audioRef.value.pause()
						imgRef.value.src = musicImg.value['pause']
					} else {
						audioRef.value.play()
						imgRef.value.src = musicImg.value['play']
					}
				}
				playStatus.value = !playStatus.value
			}
			return { musicUrl, audioRef, controlMusic, imgRef, playStatus }
		}
	}
</script>
<style scoped lang="less">
	// 元素持续旋转关键帧
	@keyframes rotation {
		from {
			transform: rotate(0deg);
		}
		to {
			transform: rotate(360deg);
		}
	}
	.img-box {
		width: 27px;
		height: 27px;
		img {
			width: 100%;
			height: 100%;
		}
	}
	// 旋转类
	.rotate {
		animation: rotation 3s linear infinite;
	}
</style>

避雷

我一开始直接在watchEffect监听audio的值 有值就直接调用play()
控制台报错

play() failed because the user didn’t interact with the document first.

内容大致意思是开发者不能利用手中权限去给用户造成噪音干扰,首次加载页面需要用户和audio/video进行交互
我这边就设置为点击音乐图标后再播放音乐

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值