VUE2 + howler.js 播放音频 自动播放
<div
id="audio_btn"
:class="audioClass"
@click="audioClick"
/>
安装(howler.js官网:GitHub - goldfire/howler.js: Javascript audio library for the modern web.)
npm install howler
<script>
import { Howl } from 'howler'
export default {
data() {
url:'', //mp3地址
audioPlay: true, //播放状态
soundBgm: null, //audio js
audioClass: '' //audio class
},
created() {
this.newAudioDom()
},
methods: {
/** audio定义 */
newAudioDom() {
this.soundBgm = new Howl({
src: [this.url],
loop: true, //自动播放
preload: true,
})
// 播放(强制自动播放)
this.soundBgm.play()
this.audioClass = 'rotate'
},
/** 视频播放 */
audioClick() {
if (this.audioPlay) {
// 暂停
this.soundBgm.pause()
this.audioClass = 'rotate rotate-pause'
} else {
// 播放
this.soundBgm.play()
this.audioClass = 'rotate'
}
this.audioPlay = !this.audioPlay
}
},
beforeDestroy() {
// 销毁
this.soundBgm.unload()
},
}
</script>
<style lang="less" scoped>
#audio_btn {
width: 35px;
height: 35px;
position: absolute;
right: 14px;
background-image: url(../../assets/video/music.png);
background-size: contain;
}
.rotate {
-webkit-animation: rotating 10s linear infinite;
-moz-animation: rotating 10s linear infinite;
-o-animation: rotating 10s linear infinite;
animation: rotating 10s linear infinite;
}
@-webkit-keyframes rotating {
from {
-webkit-transform: rotate(0);
}
to {
-webkit-transform: rotate(360deg);
}
}
@keyframes rotating {
from {
transform: rotate(0);
}
to {
transform: rotate(360deg);
}
}
@-moz-keyframes rotating {
from {
-moz-transform: rotate(0);
}
to {
-moz-transform: rotate(360deg);
}
}
.rotate-pause {
animation-play-state: paused !important;
-webkit-animation-play-state: paused !important; /* Safari 和 Chrome */
}
</style>