chore: 可以上传播放版本

This commit is contained in:
2025-12-15 18:26:49 +08:00
parent 5f6d43e66b
commit 2d417cd631
4 changed files with 76 additions and 6 deletions

View File

@@ -3,7 +3,7 @@ class MusicPlayer {
constructor() {
this.audio = null;
this.isPlaying = false;
this.defaultPath = "/assets/music/background.mp3";
this.defaultPath = "";
this.enabled = false;
this.volume = 0.5; // 默认音量50%
}
@@ -23,36 +23,55 @@ class MusicPlayer {
* @param {boolean} enabled 播放开关
*/
initMusicConfig(filePath, enabled, volume = 0.5) {
console.log("初始化音乐配置:", { filePath, enabled, volume });
this.enabled = enabled;
this.volume = volume;
// 确保音量是数字类型
this.volume = typeof volume === 'string' ? parseFloat(volume) : volume;
console.log("处理后的音量值:", this.volume, "类型:", typeof this.volume);
let validPath = this.defaultPath;
if (filePath && filePath.endsWith('.mp3')) {
validPath = filePath;
} else if (filePath) {
console.warn(`音乐路径无效非MP3格式${filePath},使用兜底路径`);
}
console.log("使用的音乐路径:", validPath);
if (this.audio) {
this.audio.pause();
this.audio = null;
}
this.audio = new Audio(validPath);
this.audio.loop = true;
this.audio.volume = this.volume;
console.log("音频对象创建完成,音量设置为:", this.audio.volume);
}
/**
* 播放音乐(保留原有逻辑,适配开关)
*/
play() {
console.log("调用 play 方法,当前状态:", { enabled: this.enabled, hasAudio: !!this.audio, isPlaying: this.isPlaying });
if (!this.enabled) {
console.log("首页播放开关未开启,跳过音乐播放");
return;
}
if (!this.audio) {
console.warn("音频对象未初始化");
this.initMusicConfig(this.defaultPath, false);
console.warn("未初始化音乐配置,使用兜底路径且关闭播放开关");
return;
}
console.log("音频源路径:", this.audio.src);
console.log("音频就绪状态:", this.audio.readyState);
if (!this.isPlaying) {
this.audio.play()
.then(() => {
@@ -61,8 +80,15 @@ class MusicPlayer {
})
.catch(err => {
console.error("音乐播放失败(浏览器自动播放限制/路径错误):", err);
console.error("错误详情:", {
name: err.name,
message: err.message,
code: err.code
});
this.isPlaying = false;
});
} else {
console.log("音乐已在播放中");
}
}
@@ -93,8 +119,10 @@ setMuted(muted) {
*/
setVolume(volume) {
if (this.audio) {
// 确保音量是数字类型
const numericVolume = typeof volume === 'string' ? parseFloat(volume) : volume;
// 限制音量范围在0.0到1.0之间
this.volume = Math.max(0, Math.min(1, volume));
this.volume = Math.max(0, Math.min(1, numericVolume));
this.audio.volume = this.volume;
console.log(`音乐音量已设置为: ${Math.round(this.volume * 100)}%`);
}