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进行交互
我这边就设置为点击音乐图标后再播放音乐