diff --git a/components/QianmenScene.vue b/components/QianmenScene.vue index 09dc92d..1db829c 100644 --- a/components/QianmenScene.vue +++ b/components/QianmenScene.vue @@ -82,7 +82,8 @@ const toggleMusic = () => { if (!musicPlayer.value) { // 创建音频对象 musicPlayer.value = uni.createInnerAudioContext() - musicPlayer.value.src = '/static/music/bgm1.mp3' + const bgmUrl = new URL('/static/music/bgm1.mp3', import.meta.url) + musicPlayer.value.src = bgmUrl.href musicPlayer.value.loop = false // 监听播放结束 diff --git a/components/SinglePageContainer.vue b/components/SinglePageContainer.vue index 3964f6c..b1dbd90 100644 --- a/components/SinglePageContainer.vue +++ b/components/SinglePageContainer.vue @@ -57,6 +57,10 @@ const isAutoScrolling = ref(false) const showLoading = ref(true) // 是否已完成图片加载 const isImagesLoaded = ref(false) +// 音乐播放状态 +const isMusicPlaying = ref(false) +// 音乐播放器实例 +const audioPlayer = ref(null) // 推荐关键词 @@ -261,9 +265,62 @@ const initPage = () => { console.log('页面准备就绪') } +// 初始化音乐播放器 +const initMusicPlayer = () => { + try { + // 创建音频播放器实例 + audioPlayer.value = uni.createInnerAudioContext() + const bgmUrl = new URL('/static/music/bgm1.mp3', import.meta.url) + audioPlayer.value.src = bgmUrl.href + audioPlayer.value.loop = true + + // 播放完成事件 + audioPlayer.value.onEnded(() => { + audioPlayer.value.seek(0) + audioPlayer.value.play() + }) + + // 播放错误事件 + audioPlayer.value.onError((err) => { + console.error('音乐播放错误:', err) + }) + + console.log('音乐播放器初始化完成') + } catch (error) { + console.error('初始化音乐播放器失败:', error) + } +} + +// 播放/暂停音乐 +const toggleMusic = () => { + if (!audioPlayer.value) { + initMusicPlayer() + } + + if (isMusicPlaying.value) { + // 暂停音乐 + audioPlayer.value.pause() + isMusicPlaying.value = false + console.log('音乐已暂停') + } else { + // 播放音乐 + audioPlayer.value.play() + isMusicPlaying.value = true + console.log('音乐已开始播放') + } +} + // 组件挂载后初始化 onMounted(() => { console.log('SinglePageContainer 组件挂载') + + // 初始化音乐播放器 + initMusicPlayer() + + // 自动开始播放音乐 + setTimeout(() => { + toggleMusic() + }, 1000) }) // 处理滚动事件(从下往上滑动) @@ -505,6 +562,15 @@ onUnmounted(() => {