yyl
6 天以前 7eee9563a2600427bbd4d7dc1a08ca501975aac7
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
using UnityEngine;
using System.Collections.Generic;
 
/// <summary>
/// 战斗音效管理器
/// 职责:播放战斗中的短促技能动作和特效音效
/// </summary>
public class BattleSoundManager
{
    private BattleField battleField;
    private GameObject audioSourceObject;
    
    // 音效池配置
    private const int INITIAL_AUDIO_POOL = 15; // 初始池大小
    private const int MAX_AUDIO_SOURCES = 30; // AudioSource 总数上限
    private Queue<AudioSource> audioSourcePool = new Queue<AudioSource>();
    private List<AudioSource> activeAudioSources = new List<AudioSource>();
    
    // 同一音效同时播放的最大数量
    private const int MAX_SAME_AUDIO_COUNT = 3;
    // 记录每个音效ID当前播放的AudioSource
    private Dictionary<int, List<AudioSource>> audioIdToSources = new Dictionary<int, List<AudioSource>>();
    
    // 音频剪辑缓存
    private Dictionary<int, AudioClip> audioClipCache = new Dictionary<int, AudioClip>();
    
    // 当前播放速度
    private float currentSpeedRatio = 1f;
    
    // 是否有焦点
    private bool hasFocus = true;
    
    public BattleSoundManager(BattleField _battleField)
    {
        battleField = _battleField;
        Debug.Log($"<color=cyan>BattleSoundManager [{battleField.guid}]: 构造函数 - 初始焦点状态={battleField.IsFocus()}</color>");
        InitializeAudioSources();
        
        // 监听战场速度变化
        if (battleField != null)
        {
            battleField.OnSpeedRatioChange -= OnSpeedRatioChanged;
            battleField.OnSpeedRatioChange += OnSpeedRatioChanged;
            battleField.OnFocusChange -= OnFocusChanged;
            battleField.OnFocusChange += OnFocusChanged;
            currentSpeedRatio = battleField.speedRatio;
            hasFocus = battleField.IsFocus();
        }
        
#if UNITY_EDITOR
        // 监听编辑器暂停事件
        UnityEditor.EditorApplication.pauseStateChanged -= OnEditorPauseStateChanged;
        UnityEditor.EditorApplication.pauseStateChanged += OnEditorPauseStateChanged;
#endif
    }
    
#if UNITY_EDITOR
    /// <summary>
    /// 编辑器暂停状态变化回调
    /// </summary>
    private void OnEditorPauseStateChanged(UnityEditor.PauseState pauseState)
    {
        if (pauseState == UnityEditor.PauseState.Paused)
        {
            Debug.Log($"<color=yellow>BattleSoundManager [{battleField.guid}]: 编辑器暂停,停止所有音效</color>");
            for (int i = activeAudioSources.Count - 1; i >= 0; i--)
            {
                var source = activeAudioSources[i];
                if (source != null)
                {
                    source.Stop();
                }
            }
        }
        else if (pauseState == UnityEditor.PauseState.Unpaused)
        {
            Debug.Log($"<color=green>BattleSoundManager [{battleField.guid}]: 编辑器恢复</color>");
            for (int i = activeAudioSources.Count - 1; i >= 0; i--)
            {
                var source = activeAudioSources[i];
                if (source != null)
                {
                    source.Play();
                }
            }            
        }
    }
#endif
    
    /// <summary>
    /// 初始化音频源池
    /// </summary>
    private void InitializeAudioSources()
    {
        // 使用战场根节点作为 AudioSource 的载体
        audioSourceObject = battleField.battleRootNode.gameObject;
        
        // 创建初始音频源池
        for (int i = 0; i < INITIAL_AUDIO_POOL; i++)
        {
            var source = audioSourceObject.AddComponent<AudioSource>();
            source.playOnAwake = false;
            source.loop = false;
            source.spatialBlend = 0f; // 2D音效
            audioSourcePool.Enqueue(source);
        }
        Debug.Log($"<color=cyan>BattleSoundManager [{battleField.guid}]: 初始化了 {INITIAL_AUDIO_POOL} 个 AudioSource</color>");
    }
    
    /// <summary>
    /// 每帧运行,清理已完成的音频源
    /// </summary>
    public void Run()
    {
        // 每帧清理,性能开销很小
        CleanupFinishedAudioSources();
    }
    
    
    /// <summary>
    /// 播放特效音效
    /// </summary>
    /// <param name="audioId">音效ID</param>
    public void PlayEffectSound(int audioId, bool pitchControl = true)
    {
        if (audioId <= 0)
        {
            return;
        }
        PlaySound(audioId, pitchControl);
    }
    
    /// <summary>
    /// 核心播放方法
    /// </summary>
    private void PlaySound(int audioId, bool pitchControl)
    {
        // 检查是否有焦点,无焦点时不播放
        if (!hasFocus)
        {
            Debug.Log($"<color=yellow>BattleSoundManager [{battleField.guid}]: 无焦点,拒绝播放音效 {audioId}</color>");
            return;
        }
        
        // 检查该音效是否已达到播放上限
        if (!CanPlayAudio(audioId))
        {
            Debug.Log($"<color=yellow>BattleSoundManager [{battleField.guid}]: 音效 {audioId} 达到播放上限,拒绝播放</color>");
            return;
        }
        
        var audioClip = GetAudioClip(audioId);
        if (audioClip == null)
        {
            Debug.Log($"<color=red>BattleSoundManager [{battleField.guid}]: 无法加载音效 {audioId}</color>");
            return;
        }
        
        // 从池中获取可用的音频源
        AudioSource source = GetAvailableAudioSource();
        if (source == null)
        {
            Debug.Log($"<color=red>BattleSoundManager [{battleField.guid}]: 无法获取AudioSource,池数量={audioSourcePool.Count},活跃数量={activeAudioSources.Count}</color>");
            return;
        }
        
        // 设置音量(使用音效音量设置)
        source.volume = SystemSetting.Instance.GetSoundEffect();
        
        // 设置播放速度,使用pitch来控制
        // pitch范围建议在0.5-2.0之间以避免失真
        if (pitchControl)
        {
            float pitch = Mathf.Clamp(currentSpeedRatio, 0.5f, 2.0f);
            source.pitch = pitch;
        }
        else
        {
            source.pitch = 1.0f;
        }
        
        // 设置音频剪辑并播放(使用 Play() 而不是 PlayOneShot(),以便 isPlaying 状态正确)
        source.clip = audioClip;
        source.Play();
        
        Debug.Log($"<color=green>BattleSoundManager [{battleField.guid}]: 播放音效 {audioId} - {audioClip.name}</color>");
        
        // 标记为活跃
        if (!activeAudioSources.Contains(source))
        {
            activeAudioSources.Add(source);
        }
        
        // 记录该音效ID与AudioSource的关联
        if (!audioIdToSources.ContainsKey(audioId))
        {
            audioIdToSources[audioId] = new List<AudioSource>();
        }
        audioIdToSources[audioId].Add(source);
    }
    
    /// <summary>
    /// 获取音频剪辑(优先从缓存获取)
    /// </summary>
    private AudioClip GetAudioClip(int audioId)
    {
        // 先从缓存中查找
        if (audioClipCache.TryGetValue(audioId, out AudioClip cachedClip))
        {
            return cachedClip;
        }
        
        // 缓存中没有,则加载并缓存
        var audioClip = LoadAudioClip(audioId);
        if (audioClip != null)
        {
            audioClipCache[audioId] = audioClip;
        }
        return audioClip;
    }
    
    /// <summary>
    /// 检查是否可以播放该音效
    /// </summary>
    private bool CanPlayAudio(int audioId)
    {
        if (!audioIdToSources.ContainsKey(audioId))
        {
            return true;
        }
        
        // 过滤掉已经停止播放的AudioSource
        var sources = audioIdToSources[audioId];
        sources.RemoveAll(s => s == null || !s.isPlaying);
        
        // 检查同时播放的数量
        return sources.Count < MAX_SAME_AUDIO_COUNT;
    }
    
    /// <summary>
    /// 加载音频剪辑
    /// </summary>
    private AudioClip LoadAudioClip(int audioId)
    {
        var config = AudioConfig.Get(audioId);
        if (config == null)
            return null;
        
        AudioClip audioClip = ResManager.Instance.LoadAsset<AudioClip>(
            "Audio/" + config.Folder,
            config.Audio,
            false
        );
        
        return audioClip;
    }
    
    /// <summary>
    /// 获取可用的音频源
    /// </summary>
    private AudioSource GetAvailableAudioSource()
    {
        // 检查 audioSourceObject 是否仍然有效(Unity 对象可能被销毁但引用不为 null)
        if (audioSourceObject == null || !audioSourceObject)
        {
            Debug.Log($"<color=red>BattleSoundManager [{battleField.guid}]: audioSourceObject 已被销毁或无效!尝试重新获取</color>");
            // 尝试重新获取
            if (battleField != null && battleField.battleRootNode != null)
            {
                audioSourceObject = battleField.battleRootNode.gameObject;
                Debug.Log($"<color=green>BattleSoundManager [{battleField.guid}]: 重新获取 audioSourceObject 成功</color>");
            }
            else
            {
                Debug.Log("BattleSoundManager: 无法重新获取 audioSourceObject");
                return null;
            }
        }
        
        // 尝试从池中获取
        while (audioSourcePool.Count > 0)
        {
            var source = audioSourcePool.Dequeue();
            // 检查 AudioSource 是否仍然有效(真机上可能被销毁)
            if (source != null)
            {
                return source;
            }
            Debug.Log($"<color=orange>BattleSoundManager [{battleField.guid}]: 池中的AudioSource已被销毁,跳过</color>");
        }
        
        // 计算当前总的 AudioSource 数量
        int totalAudioSources = audioSourceObject.GetComponents<AudioSource>().Length;
        
        if (totalAudioSources >= MAX_AUDIO_SOURCES)
        {
            // 达到上限,不再创建,丢弃这次播放请求
            Debug.Log($"BattleSoundManager: AudioSource 数量已达上限 {MAX_AUDIO_SOURCES},无法播放新音效");
            return null;
        }
        
        // 在 battleRootNode 上动态创建新的 AudioSource
        var newSource = audioSourceObject.AddComponent<AudioSource>();
        newSource.playOnAwake = false;
        newSource.loop = false;
        newSource.spatialBlend = 0f; // 2D音效
        
        Debug.Log($"<color=cyan>BattleSoundManager [{battleField.guid}]: 动态创建新AudioSource,当前总数={totalAudioSources + 1}</color>");
        
        return newSource;
    }
    
    /// <summary>
    /// 清理已播放完成的音频源
    /// </summary>
    private void CleanupFinishedAudioSources()
    {
        // 清理 activeAudioSources 列表
        for (int i = activeAudioSources.Count - 1; i >= 0; i--)
        {
            var source = activeAudioSources[i];
            if (source == null || !source.isPlaying)
            {
                activeAudioSources.RemoveAt(i);
                if (source != null)
                {
                    // 清空 clip 引用,释放内存
                    source.Stop();
                    source.clip = null;
                    audioSourcePool.Enqueue(source);
                }
            }
        }
        
        // 清理 audioIdToSources 中已停止播放的 AudioSource
        var keysToRemove = new List<int>();
        foreach (var kvp in audioIdToSources)
        {
            kvp.Value.RemoveAll(s => s == null || !s.isPlaying);
            if (kvp.Value.Count == 0)
            {
                keysToRemove.Add(kvp.Key);
            }
        }
        
        // 移除空的音效ID记录
        foreach (var key in keysToRemove)
        {
            audioIdToSources.Remove(key);
        }
    }
    
    /// <summary>
    /// 战场速度变化回调
    /// </summary>
    private void OnSpeedRatioChanged(float newSpeedRatio)
    {
        currentSpeedRatio = newSpeedRatio;
        
        // 更新所有正在播放的音效的速度
        foreach (var source in activeAudioSources)
        {
            if (source != null && source.isPlaying)
            {
                float pitch = Mathf.Clamp(newSpeedRatio, 0.5f, 2.0f);
                source.pitch = pitch;
            }
        }
    }
    
    /// <summary>
    /// 焦点变化回调
    /// </summary>
    private void OnFocusChanged(bool isFocus)
    {
        Debug.Log($"<color=magenta>BattleSoundManager [{battleField.guid}]: OnFocusChanged({isFocus}) - 当前活跃音效数={activeAudioSources.Count}</color>");
        
        hasFocus = isFocus;
        
        // 失去焦点时,停止所有正在播放的音效
        if (!hasFocus)
        {
            Debug.Log($"<color=red>BattleSoundManager [{battleField.guid}]: 失去焦点,准备停止所有音效</color>");
            StopAllSounds();
        }
        else
        {
            Debug.Log($"<color=green>BattleSoundManager [{battleField.guid}]: 获得焦点</color>");
        }
    }
    
    /// <summary>
    /// 停止所有音效
    /// </summary>
    public void StopAllSounds()
    {
        int activeCount = activeAudioSources.Count;
        int totalStopped = 0;
        
        // 不依赖列表,直接停止 GameObject 上的所有 AudioSource
        if (audioSourceObject != null)
        {
            var allSources = audioSourceObject.GetComponents<AudioSource>();
            Debug.Log($"<color=red>BattleSoundManager [{battleField.guid}]: StopAllSounds - GameObject上共有 {allSources.Length} 个AudioSource</color>");
            
            foreach (var source in allSources)
            {
                if (source != null)
                {
                    if (source.isPlaying)
                    {
                        Debug.Log($"<color=red>  停止正在播放的: {source.clip?.name}</color>");
                        totalStopped++;
                    }
                    source.Stop();
                    source.clip = null;
                }
            }
        }
        
        Debug.Log($"<color=red>BattleSoundManager [{battleField.guid}]: StopAllSounds - 活跃列表={activeCount}, 实际停止={totalStopped}</color>");
        
        // 清空所有列表
        activeAudioSources.Clear();
        audioIdToSources.Clear();
        
        // 重建对象池
        audioSourcePool.Clear();
        if (audioSourceObject != null)
        {
            var allSources = audioSourceObject.GetComponents<AudioSource>();
            foreach (var source in allSources)
            {
                if (source != null)
                {
                    audioSourcePool.Enqueue(source);
                }
            }
        }
        
        Debug.Log($"<color=red>BattleSoundManager [{battleField.guid}]: StopAllSounds 完成</color>");
    }
    
    /// <summary>
    /// 设置音量
    /// </summary>
    public void SetVolume(float volume)
    {
        volume = Mathf.Clamp01(volume);
        foreach (var source in activeAudioSources)
        {
            if (source != null)
            {
                source.volume = volume;
            }
        }
    }
    
    /// <summary>
    /// 释放资源
    /// </summary>
    public void Release()
    {
        Debug.Log($"<color=orange>BattleSoundManager [{battleField.guid}]: Release 开始</color>");
        
        if (battleField != null)
        {
            battleField.OnSpeedRatioChange -= OnSpeedRatioChanged;
            battleField.OnFocusChange -= OnFocusChanged;
        }
        
#if UNITY_EDITOR
        // 取消订阅编辑器暂停事件
        UnityEditor.EditorApplication.pauseStateChanged -= OnEditorPauseStateChanged;
#endif
        
        StopAllSounds();
        
        // 销毁所有 AudioSource 组件
        if (audioSourceObject != null)
        {
            var sources = audioSourceObject.GetComponents<AudioSource>();
            Debug.Log($"<color=orange>BattleSoundManager [{battleField.guid}]: 销毁 {sources.Length} 个 AudioSource 组件</color>");
            foreach (var source in sources)
            {
                if (source != null)
                {
                    GameObject.Destroy(source);
                }
            }
            audioSourceObject = null;
        }
        
        audioSourcePool.Clear();
        activeAudioSources.Clear();
        audioIdToSources.Clear();
        audioClipCache.Clear();
        
        Debug.Log($"<color=orange>BattleSoundManager [{battleField.guid}]: Release 完成</color>");
    }
}