@@ -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
0 commit comments