【需求】h5页面添加背景音乐,支持微信、QQ、各种APP。
【实现思路】1、通过audio标签,设置自动播放,是一种方法,但是此方法只适合微信、QQ,并不兼容我司的APP,需要主动触发下播放事件。
2、针对可以自动播放的渠道,通过this.audio.addEventListene监听playing事件,控制小喇叭的状态。
【知识点】audio标签、addEventListener、classList
【代码】封装了一个公共组件:
1 <template> 2 <div class="music"> 3 <audio src={{musicsrc}} id="Jaudio" class="media-audio" preload loop="loop" hidden="false"></audio> 4 <div class="icon"></div> 5 </div> 6 </template> 7 <script> 8 /* eslint-disable */ 9 export default{ 10 data() { 11 return {} 12 }, 13 props: { 14 musicsrc: {} 15 }, 16 methods: { 17 // 音乐背景 18 play() { 19 this.audio.play() 20 this.icon.classList.add(‘play‘); 21 this.icon.classList.remove(‘stop‘); 22 }, 23 stop() { 24 this.audio.pause() 25 this.icon.classList.add(‘stop‘); 26 this.icon.classList.remove(‘play‘); 27 }, 28 audioAutoPlay() { 29 this.audio.play(); 30 var that=this; 31 //控制小喇叭的播放状态 32 this.audio.addEventListener("playing", function(){ 33 that.icon.classList.add(‘play‘); 34 that.icon.classList.remove(‘stop‘); 35 }); 36 this.audio.addEventListener("pause", function(){ 37 that.icon.classList.add(‘stop‘); 38 that.icon.classList.remove(‘play‘); 39 }); 40 document.addEventListener("WeixinJSBridgeReady", function () { 41 that.audio.play(); 42 this.icon.classList.add(‘play‘); 43 this.icon.classList.remove(‘stop‘); 44 }, false); 45 this.icon.addEventListener("click", () => { 46 if (this.audio.paused) { 47 this.play() 48 } else { 49 this.stop() 50 } 51 }, false); 52 // 触发播放音乐效果,解决浏览器或者APP自动播放问题 53 document.addEventListener("touchstart", () => { 54 if(!this.isPlay) { 55 this.play(); 56 this.isPlay = true; 57 } 58 }, false) 59 }, 60 61 }, 62 ready() { 63 this.audio = window.document.querySelector(‘.media-audio‘); 64 this.icon = window.document.querySelector(‘.icon‘); 65 this.audioAutoPlay(); 66 } 67 } 68 </script> 69 <style rel="stylesheet/scss" lang="scss"> 70 .music { 71 position:fixed; 72 z-index:1000; 73 top:50px; 74 right:20px; 75 76 .icon{ 77 width:60px; 78 height:50px; 79 background:url(‘https://pic.51zhangdan.com/u51/storage/dd/df9e5296-1fa9-f3c4-6151-afeab9c2f34d.png‘) no-repeat; 80 background-size: 100%; 81 &.play{ 82 animation: 4s linear 0s normal none infinite rotate; 83 // animation-fill-mode:forwards; 84 // animation-play-state: running; 85 } 86 &.stop{ 87 // animation: 4s linear 0s normal none infinite rotate; 88 // animation-fill-mode:forwards; 89 // animation-play-state: paused; 90 } 91 } 92 } 93 94 @keyframes rotate{ 95 from{transform:rotate(0deg)} 96 to{transform:rotate(360deg)} 97 } 98 </style>
组件调用:
1 <template> 2 <bgmusic :musicsrc=‘musicbg‘></bgmusic> 3 </template> 4 <script> 5 import bgmusic from ‘../../components/music/bgmusic.vue‘ 6 7 export default { 8 data() { 9 return { 10 musicbg: "../../assets/music/musicbg.mp3", 11 } 12 } 13 } 14 15 </script>
时间: 2024-11-05 15:55:49