chore: 支持背景音乐音量设置
This commit is contained in:
@@ -5,6 +5,7 @@ class MusicPlayer {
|
||||
this.isPlaying = false;
|
||||
this.defaultPath = "/assets/music/background.mp3";
|
||||
this.enabled = false;
|
||||
this.volume = 0.5; // 默认音量50%
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -13,7 +14,7 @@ class MusicPlayer {
|
||||
*/
|
||||
init(path) {
|
||||
// 组件调用 init 时,复用已有的 initMusicConfig,开关状态先传 this.enabled(后续组件会通过配置更新)
|
||||
this.initMusicConfig(path, this.enabled);
|
||||
this.initMusicConfig(path, this.enabled, this.volume);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -21,8 +22,9 @@ class MusicPlayer {
|
||||
* @param {string} filePath 音乐路径
|
||||
* @param {boolean} enabled 播放开关
|
||||
*/
|
||||
initMusicConfig(filePath, enabled) {
|
||||
initMusicConfig(filePath, enabled, volume = 0.5) {
|
||||
this.enabled = enabled;
|
||||
this.volume = volume;
|
||||
let validPath = this.defaultPath;
|
||||
if (filePath && filePath.endsWith('.mp3')) {
|
||||
validPath = filePath;
|
||||
@@ -35,6 +37,7 @@ class MusicPlayer {
|
||||
}
|
||||
this.audio = new Audio(validPath);
|
||||
this.audio.loop = true;
|
||||
this.audio.volume = this.volume;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -83,6 +86,20 @@ setMuted(muted) {
|
||||
console.log(muted ? "音乐已静音" : "音乐已取消静音");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置音量
|
||||
* @param {number} volume 音量值 (0.0 到 1.0)
|
||||
*/
|
||||
setVolume(volume) {
|
||||
if (this.audio) {
|
||||
// 限制音量范围在0.0到1.0之间
|
||||
this.volume = Math.max(0, Math.min(1, volume));
|
||||
this.audio.volume = this.volume;
|
||||
console.log(`音乐音量已设置为: ${Math.round(this.volume * 100)}%`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 新增:stop 方法(组件 onUnmounted 调用,暂停+重置进度)
|
||||
*/
|
||||
@@ -124,7 +141,7 @@ setMuted(muted) {
|
||||
console.error("更新的音乐路径无效(非MP3格式):", newPath);
|
||||
return;
|
||||
}
|
||||
this.initMusicConfig(newPath, this.enabled);
|
||||
this.initMusicConfig(newPath, this.enabled, this.volume);
|
||||
console.log("音乐路径已更新为:", newPath);
|
||||
if (this.enabled && this.isPlaying) {
|
||||
this.pause();
|
||||
|
||||
Reference in New Issue
Block a user