Skip to content

Commit e11c52b

Browse files
committed
🐞 fix: 自动播放提前
1 parent 9d02766 commit e11c52b

2 files changed

Lines changed: 17 additions & 12 deletions

File tree

src/utils/audioManager.ts

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -116,9 +116,12 @@ class AudioManager {
116116
/**
117117
* 加载并播放音频
118118
* @param url 音频地址
119-
* @param options 播放选项 (fadeIn: 是否渐入, fadeDuration: 渐入时长)
119+
* @param options 播放选项 (fadeIn: 是否渐入, fadeDuration: 渐入时长, autoPlay: 是否自动播放)
120120
*/
121-
public async play(url?: string, options: { fadeIn?: boolean; fadeDuration?: number } = {}) {
121+
public async play(
122+
url?: string,
123+
options: { fadeIn?: boolean; fadeDuration?: number; autoPlay?: boolean } = {},
124+
) {
122125
if (!this.isInitialized) this.init();
123126

124127
// 如果上下文被挂起,则恢复
@@ -131,8 +134,11 @@ class AudioManager {
131134
this.audioElement.load();
132135
}
133136

137+
// 自动播放控制
138+
const shouldPlay = options.autoPlay ?? true;
139+
134140
// 处理渐入
135-
if (options.fadeIn && this.gainNode && this.audioCtx) {
141+
if (shouldPlay && options.fadeIn && this.gainNode && this.audioCtx) {
136142
this.gainNode.gain.cancelScheduledValues(this.audioCtx.currentTime);
137143
this.gainNode.gain.setValueAtTime(0, this.audioCtx.currentTime);
138144
this.gainNode.gain.linearRampToValueAtTime(
@@ -144,11 +150,13 @@ class AudioManager {
144150
this.gainNode.gain.setValueAtTime(this.volume, this.audioCtx.currentTime);
145151
}
146152

147-
try {
148-
await this.audioElement?.play();
149-
} catch (error) {
150-
console.error("AudioManager: 播放失败", error);
151-
throw error;
153+
if (shouldPlay) {
154+
try {
155+
await this.audioElement?.play();
156+
} catch (error) {
157+
console.error("AudioManager: 播放失败", error);
158+
throw error;
159+
}
152160
}
153161
}
154162

src/utils/player.ts

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -174,14 +174,11 @@ class Player {
174174
if (!settingStore.showSpectrums) this.toggleOutputDevice();
175175
// 加载并播放
176176
try {
177-
await audioManager.play(src, { fadeIn: false });
177+
await audioManager.play(src, { fadeIn: false, autoPlay });
178178
// 恢复进度
179179
if (seek && seek > 0) {
180180
audioManager.seek(seek / 1000);
181181
}
182-
if (!autoPlay) {
183-
audioManager.pause();
184-
}
185182
} catch (e) {
186183
console.error("Player create failed", e);
187184
}

0 commit comments

Comments
 (0)