You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

139 lines
3.4 KiB

<template>
<view class="music-control" @click.stop="toggleMusic">
<text class="music-text" :class="{ 'rotating': isPlaying }">
{{ isPlaying ? '🎵' : '🔇' }}
</text>
</view>
</template>
<script>
export default {
name: 'MusicControl',
data() {
return {
isPlaying: false,
isAudioPlaying: false // 记录音频播放状态
}
},
mounted() {
// console.log('初始化')
// 组件挂载时同步音乐状态
this.syncMusicState();
// 检查全局音频状态
this.checkGlobalAudioState();
// 添加定时器,每秒同步一次状态
this.timer = setInterval(() => {
this.syncMusicState();
this.checkGlobalAudioState();
}, 1000);
// 监听音频播放状态变化
uni.$on('audioPlaying', this.handleAudioStateChange);
},
beforeUnmount() {
// 组件卸载前清除定时器
if (this.timer) {
clearInterval(this.timer);
}
// 移除事件监听
uni.$off('audioPlaying', this.handleAudioStateChange);
},
methods: {
syncMusicState() {
const app = getApp();
if (app && app.globalData) {
this.isPlaying = app.globalData.isMusicPlaying;
}
},
toggleMusic() {
const app = getApp();
if (!app || !app.globalData || !app.globalData.bgMusic) {
// console.error('背景音乐未初始化');
return;
}
const bgMusic = app.globalData.bgMusic;
// console.log(bgMusic)
// 先发送背景音乐切换事件,通知AudioControl组件(但不要让它恢复背景音乐)
if (this.isAudioPlaying) {
uni.$emit('backgroundMusicToggle');
// 等待一小段时间确保音频已暂停
setTimeout(() => {
// 直接基于当前组件的状态切换背景音乐
if (this.isPlaying) {
bgMusic.pause();
} else {
bgMusic.play();
}
}, 100);
} else {
// 没有音频在播放时,直接切换背景音乐
if (this.isPlaying) {
bgMusic.pause();
} else {
bgMusic.play();
}
}
},
// 处理音频状态变化
handleAudioStateChange(isAudioPlaying) {
this.isAudioPlaying = isAudioPlaying;
// console.log('音频状态变化:', isAudioPlaying);
},
// 检查全局音频状态
checkGlobalAudioState() {
try {
const app = getApp();
if (app && app.globalData && app.globalData.currentAudio) {
const globalAudio = app.globalData.currentAudio;
// 检查全局音频是否在播放
this.isAudioPlaying = !globalAudio.paused;
// console.log('检查到全局音频状态:', this.isAudioPlaying);
} else {
this.isAudioPlaying = false;
}
} catch (error) {
// console.error('检查全局音频状态失败:', error);
this.isAudioPlaying = false;
}
}
}
}
</script>
<style scoped>
.music-control {
position: fixed;
right: 30rpx;
bottom: 210rpx;
width: 80rpx;
height: 80rpx;
border-radius: 50%;
background-color: rgba(0, 0, 0, 0.3);
display: flex;
align-items: center;
justify-content: center;
z-index: 998;
}
.music-text {
font-size: 40rpx;
}
.rotating {
animation: rotate 3s linear infinite;
}
@keyframes rotate {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
</style>