欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 前端技术 > vue >内容正文

vue

vue不同页面切换,背景音乐连续播放不间断

发布时间:2024/1/8 vue 54 豆豆
生活随笔 收集整理的这篇文章主要介绍了 vue不同页面切换,背景音乐连续播放不间断 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

最近遇到了这样一个需求,就是h5不同页面之间跳转,要求bgm连续播放不间断。 不知道大家是怎么处理的呢?
我之前想的是,在每个页面都写一个audio标签,然后切换页面的时候存一下当前音乐的播放进度,到下一个页面再给音乐写入开始时间。

<template><audio loop="loop" preload="preload" id="bgmusic" controls="controls" ref="MusicPlay" style="display: none;"><source src="xxx.mp3" type="audio/mpeg"></audio><span @click="goIndex"></span> </template><script> mounted(){this.soundBgm = document.getElementById("bgmusic");//判断本地是否有存储过音频播放时间if(sessionStorage.bgmstart == 'true'){this.current = 'musicplay';if (sessionStorage.bgmTime == null) {//若没有时,从头自动播放this.soundBgm.currentTime = 0;this.soundBgm.play();} else {//若有存储的则,取出本地存储的音频播放的暂停时间var curTime = window.sessionStorage.getItem("bgmTime");sessionStorage.setItem('bgmPlay', this.soundBgm.bgmPlay);//从暂停时间开始接着播放this.soundBgm.currentTime += curTime;this.soundBgm.play();}}},methods:{//页面跳转时将本页面音频最后截至时间存储下来fun() {this.soundBgm.pause();sessionStorage.setItem('bgmPlay', this.soundBgm.bgmPlay);sessionStorage.setItem('bgmTime', this.soundBgm.bgmPlay ? this.soundBgm.currentTime + this.soundBgm.context.currentTime - this.soundBgm.startTime : this.soundBgm.currentTime);},// 跳转goIndex() {this.fun();this.$router.push({path: `/xxx`,});}}</script>

但是这样第一是不同页面切换的时候,音乐有很明显的卡顿。第二就是iOS设置currentTime没反应,不知道为什么一直是0。有木有大佬可以讲一下这样为什么iOS不能适配啊(其实大家也能看出来 我这里写的非常混乱,原生夹杂vue…真的是很晕了)

后来请教了一个大佬指点了一下 ,正确的操作应该是 在app.vue里设置全局audio

<template><div id="app"><router-view /><audioloop="loop"preload="preload"id="bgmusic"controls="controls"ref="MusicPlay"style="display: none;"><sourcesrc="xxx.mp3"type="audio/mpeg"/></audio></div> </template>

其他页面直接用this.$parent去调用然后播放

this.$parent.$refs.MusicPlay.play(); this.$parent.$refs.MusicPlay.pause();

按照逻辑功能的不同,在合适的位置写入即可

总结

以上是生活随笔为你收集整理的vue不同页面切换,背景音乐连续播放不间断的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。