Repository navigation
Expand file tree
/
Copy pathAudioManager.cs
More file actions
974 lines (833 loc) · 33.2 KB
/
Copy pathAudioManager.cs
File metadata and controls
974 lines (833 loc) · 33.2 KB
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
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using NAudio.CoreAudioApi;
using NAudio.CoreAudioApi.Interfaces;
using NAudio.Wave;
namespace WpfApp1
{
public class AudioOutputDeviceInfo
{
public string DeviceId { get; set; } = string.Empty;
public string FriendlyName { get; set; } = string.Empty;
public override string ToString()
{
return FriendlyName;
}
}
public class PlaybackStoppedEventArgs : EventArgs
{
public PlaybackStoppedEventArgs(int playbackSessionId, StoppedEventArgs stoppedEventArgs)
{
PlaybackSessionId = playbackSessionId;
StoppedEventArgs = stoppedEventArgs;
}
public int PlaybackSessionId { get; }
public StoppedEventArgs StoppedEventArgs { get; }
}
/// <summary>
/// 管理音频播放相关功能的类
/// </summary>
public class AudioManager : IDisposable
{
private IWavePlayer _wavePlayer;
private AudioFileReader _audioFileReader;
private WaveStream? _exclusivePlaybackProvider;
private int _selectedDeviceIndex = -1;
private string _selectedDeviceId = string.Empty;
private AudioOutputMode _outputMode = AudioOutputMode.Compatible;
private MMDevice? _wasapiDevice;
private EventHandler<StoppedEventArgs>? _wavePlayerPlaybackStoppedHandler;
private int _playbackSessionId = 0;
private const int WasapiLatencyMilliseconds = 100;
private const int AudclntBufferSizeNotAlignedHResult = unchecked((int)0x88890023);
private static readonly int[] ExclusiveProbeSampleRates = { 48000, 44100, 96000, 32000 };
private static readonly int[] ExclusiveProbeChannelCounts = { 2, 1 };
private static readonly int[] ExclusiveProbeBitDepths = { 16, 24, 32 };
public List<string> AudioDeviceNames { get; private set; } = new List<string>();
// 添加停止播放事件
public event EventHandler<PlaybackStoppedEventArgs> PlaybackStopped;
public int CurrentPlaybackSessionId => _playbackSessionId;
public bool IsPlaying => _wavePlayer != null && _wavePlayer.PlaybackState == PlaybackState.Playing;
public bool IsPaused => _wavePlayer != null && _wavePlayer.PlaybackState == PlaybackState.Paused;
public bool HasActivePlaybackSession => _wavePlayer != null && _wavePlayer.PlaybackState != PlaybackState.Stopped;
public TimeSpan CurrentTime => _audioFileReader?.CurrentTime ?? TimeSpan.Zero;
public TimeSpan TotalTime => _audioFileReader?.TotalTime ?? TimeSpan.Zero;
public AudioManager()
{
InitializeAudioPlayer();
}
private static float ClampStreamVolume(float volume)
{
return Math.Max(0.0f, Math.Min(1.0f, volume));
}
private static float VolumePercentToScalar(int volume)
{
return ClampStreamVolume(volume / 100.0f);
}
public static bool RequiresWasapiDeviceId(AudioOutputMode outputMode)
{
return outputMode == AudioOutputMode.Standard || outputMode == AudioOutputMode.Exclusive;
}
private static string GetOutputModeName(AudioOutputMode outputMode)
{
return outputMode switch
{
AudioOutputMode.Standard => "标准音频输出模式",
AudioOutputMode.Exclusive => "独占音频输出模式",
AudioOutputMode.Compatible => "兼容音频输出模式",
_ => "未知音频输出模式"
};
}
/// <summary>
/// 初始化音频播放器
/// </summary>
private void InitializeAudioPlayer(int playbackSessionId = 0)
{
// 释放旧的播放器
DisposeAudioPlayer();
_wavePlayer = _outputMode switch
{
AudioOutputMode.Compatible => CreateCompatibleAudioPlayer(),
AudioOutputMode.Standard => CreateStandardAudioPlayer(),
AudioOutputMode.Exclusive => CreateExclusiveAudioPlayer(),
_ => throw new InvalidOperationException($"不支持的音频输出模式: {_outputMode}")
};
// 添加停止事件处理
_wavePlayerPlaybackStoppedHandler = (s, e) =>
PlaybackStopped?.Invoke(s, new PlaybackStoppedEventArgs(playbackSessionId, e));
_wavePlayer.PlaybackStopped += _wavePlayerPlaybackStoppedHandler;
}
private IWavePlayer CreateCompatibleAudioPlayer()
{
try
{
// 创建新的播放器
var waveOut = new WaveOutEvent();
// 如果有选定的设备,尝试设置DeviceNumber
if (_selectedDeviceIndex >= 0)
{
// 获取可用的WaveOut设备数量
int deviceCount = WaveOut.DeviceCount;
// 确保索引在有效范围内
if (_selectedDeviceIndex < deviceCount)
{
waveOut.DeviceNumber = _selectedDeviceIndex;
}
}
return waveOut;
}
catch (Exception)
{
// 如果出现任何异常,使用默认设备
return new WaveOutEvent();
}
}
private IWavePlayer CreateStandardAudioPlayer()
{
return CreateWasapiAudioPlayer(AudioClientShareMode.Shared);
}
private IWavePlayer CreateExclusiveAudioPlayer()
{
return CreateWasapiAudioPlayer(AudioClientShareMode.Exclusive);
}
private IWavePlayer CreateWasapiAudioPlayer(AudioClientShareMode shareMode)
{
if (string.IsNullOrWhiteSpace(_selectedDeviceId))
{
throw new InvalidOperationException($"{GetOutputModeName(_outputMode)}需要先选择有效的音频设备。");
}
MMDevice? device = null;
try
{
device = GetSelectedWasapiDevice(_selectedDeviceId, _outputMode);
var wasapiOut = new WasapiOut(device, shareMode, true, WasapiLatencyMilliseconds);
_wasapiDevice = device;
device = null;
return wasapiOut;
}
catch (InvalidOperationException)
{
throw;
}
catch (Exception ex)
{
throw new InvalidOperationException($"无法初始化{GetOutputModeName(_outputMode)}设备。", ex);
}
finally
{
device?.Dispose();
}
}
private static MMDevice GetSelectedWasapiDevice(string deviceId, AudioOutputMode outputMode)
{
if (!RequiresWasapiDeviceId(outputMode))
{
throw new InvalidOperationException($"{GetOutputModeName(outputMode)}不使用 WASAPI 设备 ID。");
}
if (string.IsNullOrWhiteSpace(deviceId))
{
throw new InvalidOperationException($"{GetOutputModeName(outputMode)}需要先选择有效的音频设备。");
}
using var enumerator = new MMDeviceEnumerator();
var device = enumerator.GetDevice(deviceId);
if (device.DataFlow != DataFlow.Render || device.State != DeviceState.Active)
{
device.Dispose();
throw new InvalidOperationException($"{GetOutputModeName(outputMode)}只能使用启用中的播放设备。");
}
return device;
}
private void DisposeAudioPlayer()
{
if (_wavePlayer != null)
{
if (_wavePlayerPlaybackStoppedHandler != null)
{
_wavePlayer.PlaybackStopped -= _wavePlayerPlaybackStoppedHandler;
_wavePlayerPlaybackStoppedHandler = null;
}
_wavePlayer.Dispose();
_wavePlayer = null;
}
if (_wasapiDevice != null)
{
_wasapiDevice.Dispose();
_wasapiDevice = null;
}
}
private void DisposeExclusivePlaybackProvider()
{
if (_exclusivePlaybackProvider != null)
{
_exclusivePlaybackProvider.Dispose();
_exclusivePlaybackProvider = null;
}
}
/// <summary>
/// 加载音频设备列表
/// </summary>
public void LoadAudioDevices()
{
// 清空当前列表
AudioDeviceNames.Clear();
// 获取WaveOut设备列表
int deviceCount = WaveOut.DeviceCount;
// 添加设备名称到列表
for (int i = 0; i < deviceCount; i++)
{
var capabilities = WaveOut.GetCapabilities(i);
AudioDeviceNames.Add(capabilities.ProductName);
}
}
/// <summary>
/// 获取音频设备列表
/// </summary>
/// <returns>设备名称列表</returns>
public List<string> GetAudioDevices()
{
// 清空并重新加载设备列表
AudioDeviceNames.Clear();
// 获取WaveOut设备列表
int deviceCount = WaveOut.DeviceCount;
// 添加设备名称到列表
for (int i = 0; i < deviceCount; i++)
{
var capabilities = WaveOut.GetCapabilities(i);
AudioDeviceNames.Add(capabilities.ProductName);
}
return AudioDeviceNames;
}
/// <summary>
/// 获取标准模式可用的WASAPI播放设备列表
/// </summary>
/// <returns>WASAPI播放设备列表</returns>
public List<AudioOutputDeviceInfo> GetWasapiDevices()
{
var devices = new List<AudioOutputDeviceInfo>();
using var enumerator = new MMDeviceEnumerator();
foreach (var device in enumerator.EnumerateAudioEndPoints(DataFlow.Render, DeviceState.Active))
{
try
{
devices.Add(new AudioOutputDeviceInfo
{
DeviceId = device.ID,
FriendlyName = device.FriendlyName
});
}
finally
{
device.Dispose();
}
}
return devices;
}
public void ValidateOutputDevice(AudioOutputMode outputMode, string deviceId)
{
if (!RequiresWasapiDeviceId(outputMode))
{
return;
}
MMDevice? device = null;
try
{
device = GetSelectedWasapiDevice(deviceId, outputMode);
if (outputMode == AudioOutputMode.Standard)
{
WaveFormat mixFormat;
using (var audioClient = device.AudioClient)
{
mixFormat = audioClient.MixFormat;
}
ProbeWasapiDeviceOpen(device, AudioClientShareMode.Shared, mixFormat);
return;
}
WaveFormat exclusiveMixFormat;
using (var audioClient = device.AudioClient)
{
exclusiveMixFormat = audioClient.MixFormat;
}
if (!TryFindSupportedExclusiveFormat(device, exclusiveMixFormat, out var outputFormat))
{
throw new InvalidOperationException("未找到该设备支持的独占输出格式。");
}
ProbeWasapiDeviceOpen(device, AudioClientShareMode.Exclusive, outputFormat);
}
catch (InvalidOperationException)
{
throw;
}
catch (Exception ex)
{
throw CreateWasapiOpenException(outputMode, ex);
}
finally
{
device?.Dispose();
}
}
private static void ProbeWasapiDeviceOpen(MMDevice device, AudioClientShareMode shareMode, WaveFormat waveFormat)
{
using var wasapiOut = new WasapiOut(device, shareMode, true, WasapiLatencyMilliseconds);
wasapiOut.Init(new SilenceProvider(waveFormat));
}
private static InvalidOperationException CreateWasapiOpenException(AudioOutputMode outputMode, Exception ex)
{
string modeName = GetOutputModeName(outputMode);
if (ContainsAudioClientError(ex, AudioClientErrorCode.DeviceInUse))
{
return new InvalidOperationException($"{modeName}打开失败:设备正被其他程序占用。", ex);
}
if (ContainsAudioClientError(ex, AudioClientErrorCode.ExclusiveModeNotAllowed))
{
return new InvalidOperationException($"{modeName}打开失败:Windows 未允许应用程序独占控制该设备。", ex);
}
if (ContainsAudioClientError(ex, AudioClientErrorCode.UnsupportedFormat))
{
return new InvalidOperationException($"{modeName}打开失败:设备不支持当前输出格式。", ex);
}
if (ContainsAudioClientError(ex, AudioClientErrorCode.BufferSizeNotAligned) ||
ContainsAudioClientError(ex, AudclntBufferSizeNotAlignedHResult))
{
return new InvalidOperationException($"{modeName}打开失败:独占缓冲区大小未对齐。", ex);
}
return new InvalidOperationException($"{modeName}打开失败:{ex.Message}", ex);
}
private static bool ContainsAudioClientError(Exception ex, int errorCode)
{
for (Exception? current = ex; current != null; current = current.InnerException)
{
if (current is COMException comException && comException.ErrorCode == errorCode)
{
return true;
}
}
return false;
}
/// <summary>
/// 设置音频输出模式
/// </summary>
/// <param name="outputMode">音频输出模式</param>
public void SetOutputMode(AudioOutputMode outputMode)
{
if (_outputMode == outputMode)
{
return;
}
bool wasPlaying = _wavePlayer != null && _wavePlayer.PlaybackState == PlaybackState.Playing;
_outputMode = outputMode;
if (wasPlaying)
{
ReinitializeForOutputChange(RequiresWasapiDeviceId(outputMode));
return;
}
if (RequiresWasapiDeviceId(outputMode) && string.IsNullOrWhiteSpace(_selectedDeviceId))
{
DisposeAudioPlayer();
return;
}
InitializeAudioPlayer();
}
/// <summary>
/// 设置音频设备
/// </summary>
/// <param name="deviceName">设备名称</param>
public void SetAudioDevice(string deviceName)
{
// 查找设备名称对应的索引
int deviceIndex = -1;
if (!string.IsNullOrWhiteSpace(deviceName))
{
for (int i = 0; i < AudioDeviceNames.Count; i++)
{
if (AudioDeviceNames[i] == deviceName)
{
deviceIndex = i;
break;
}
}
}
// 保存设备索引;未找到或空设备名时重置为默认 WaveOut 设备,避免保留旧索引。
_selectedDeviceIndex = deviceIndex;
if (_outputMode == AudioOutputMode.Compatible)
{
ReinitializeForOutputChange(false);
}
}
/// <summary>
/// 设置WASAPI设备ID
/// </summary>
/// <param name="deviceId">WASAPI设备ID</param>
public void SetAudioDeviceId(string deviceId)
{
string newDeviceId = deviceId ?? string.Empty;
if (string.Equals(_selectedDeviceId, newDeviceId, StringComparison.Ordinal))
{
return;
}
_selectedDeviceId = newDeviceId;
if (RequiresWasapiDeviceId(_outputMode))
{
ReinitializeForOutputChange(true);
}
}
/// <summary>
/// 尝试根据兼容模式设备名称匹配WASAPI设备ID
/// </summary>
/// <param name="deviceName">兼容模式设备名称</param>
/// <param name="deviceId">匹配到的WASAPI设备ID</param>
/// <returns>是否匹配成功</returns>
public bool TryMatchWasapiDeviceIdByName(string deviceName, out string deviceId)
{
deviceId = string.Empty;
if (string.IsNullOrWhiteSpace(deviceName))
{
return false;
}
AudioOutputDeviceInfo? prefixMatch = null;
foreach (var device in GetWasapiDevices())
{
if (string.Equals(device.FriendlyName, deviceName, StringComparison.Ordinal))
{
deviceId = device.DeviceId;
return true;
}
if (prefixMatch == null && device.FriendlyName.StartsWith(deviceName, StringComparison.Ordinal))
{
prefixMatch = device;
}
}
if (prefixMatch != null)
{
deviceId = prefixMatch.DeviceId;
return true;
}
return false;
}
private static void AddWaveFormatCandidate(List<WaveFormat> candidates, WaveFormat? candidate)
{
if (candidate == null)
{
return;
}
if (candidate.Channels <= 0 || candidate.SampleRate <= 0 || candidate.BitsPerSample <= 0)
{
return;
}
if (candidates.Exists(existing =>
existing.SampleRate == candidate.SampleRate &&
existing.Channels == candidate.Channels &&
existing.BitsPerSample == candidate.BitsPerSample &&
existing.Encoding == candidate.Encoding))
{
return;
}
candidates.Add(candidate);
}
private static List<WaveFormat> BuildExclusiveFormatCandidates(WaveFormat sourceFormat)
{
var candidates = new List<WaveFormat>();
AddWaveFormatCandidate(candidates, sourceFormat);
foreach (int bitDepth in ExclusiveProbeBitDepths)
{
AddWaveFormatCandidate(candidates, CreateCandidateWaveFormat(sourceFormat.SampleRate, bitDepth, sourceFormat.Channels));
}
foreach (int sampleRate in ExclusiveProbeSampleRates)
{
foreach (int channels in ExclusiveProbeChannelCounts)
{
foreach (int bitDepth in ExclusiveProbeBitDepths)
{
AddWaveFormatCandidate(candidates, CreateCandidateWaveFormat(sampleRate, bitDepth, channels));
}
}
}
return candidates;
}
private static WaveFormat CreateCandidateWaveFormat(int sampleRate, int bitDepth, int channels)
{
if (bitDepth == 32)
{
return WaveFormat.CreateIeeeFloatWaveFormat(sampleRate, channels);
}
return new WaveFormatExtensible(sampleRate, bitDepth, channels);
}
private static bool TryFindSupportedExclusiveFormat(MMDevice device, WaveFormat sourceFormat, out WaveFormat supportedFormat)
{
using var audioClient = device.AudioClient;
foreach (var candidate in BuildExclusiveFormatCandidates(sourceFormat))
{
if (audioClient.IsFormatSupported(AudioClientShareMode.Exclusive, candidate))
{
supportedFormat = candidate;
return true;
}
}
supportedFormat = sourceFormat;
return false;
}
private void InitializeCurrentWavePlayerWithReader(AudioFileReader reader)
{
DisposeExclusivePlaybackProvider();
if (_outputMode != AudioOutputMode.Exclusive)
{
_wavePlayer.Init(reader);
return;
}
using var device = GetSelectedWasapiDevice(_selectedDeviceId, AudioOutputMode.Exclusive);
if (!TryFindSupportedExclusiveFormat(device, reader.WaveFormat, out var outputFormat))
{
throw new InvalidOperationException("独占音频输出模式找不到可用于播放该文件的设备格式。");
}
if (outputFormat.SampleRate == reader.WaveFormat.SampleRate &&
outputFormat.Channels == reader.WaveFormat.Channels &&
outputFormat.BitsPerSample == reader.WaveFormat.BitsPerSample &&
outputFormat.Encoding == reader.WaveFormat.Encoding)
{
_wavePlayer.Init(reader);
return;
}
// NAudio 2.2.1 WasapiOut also probes exclusive formats internally; this explicit
// resampler keeps the conversion provider alive for the full playback session.
_exclusivePlaybackProvider = new ResamplerDmoStream(reader, outputFormat);
_wavePlayer.Init(_exclusivePlaybackProvider);
}
private void ReinitializeForOutputChange(bool throwOnRestoreFailure)
{
if (_wavePlayer != null && _wavePlayer.PlaybackState == PlaybackState.Paused)
{
StopPlayback();
InitializeAudioPlayer(++_playbackSessionId);
return;
}
// 如果正在播放,需要切换设备
if (_wavePlayer != null && _wavePlayer.PlaybackState == PlaybackState.Playing)
{
// 保存当前播放状态
string? filePath = null;
float volume = 1.0f;
long position = 0;
if (_audioFileReader != null)
{
filePath = _audioFileReader.FileName;
position = _audioFileReader.Position;
volume = _audioFileReader.Volume;
}
// 停止当前播放
StopPlayback();
// 重新初始化播放器
int playbackSessionId = ++_playbackSessionId;
InitializeAudioPlayer(playbackSessionId);
// 如果有文件正在播放,恢复播放
if (filePath != null)
{
try
{
_audioFileReader = new AudioFileReader(filePath);
_audioFileReader.Position = position;
_audioFileReader.Volume = ClampStreamVolume(volume);
InitializeCurrentWavePlayerWithReader(_audioFileReader);
_wavePlayer.Play();
}
catch (Exception ex)
{
DisposeExclusivePlaybackProvider();
if (_audioFileReader != null)
{
_audioFileReader.Dispose();
_audioFileReader = null;
}
DisposeAudioPlayer();
if (throwOnRestoreFailure)
{
throw new InvalidOperationException("切换音频输出后恢复播放失败。", ex);
}
// 兼容模式沿用旧行为:忽略恢复播放时的错误
}
}
}
else
{
// 如果没有播放,只需重新初始化播放器
InitializeAudioPlayer();
}
}
/// <summary>
/// 播放音频文件
/// </summary>
/// <param name="filePath">音频文件路径</param>
/// <param name="volume">音量(0-100)</param>
public int PlayFile(string filePath, int volume)
{
// 停止当前播放
StopPlayback();
int playbackSessionId = ++_playbackSessionId;
InitializeAudioPlayer(playbackSessionId);
try
{
// 创建新的音频读取器
_audioFileReader = new AudioFileReader(filePath);
_audioFileReader.Volume = VolumePercentToScalar(volume);
// 初始化播放器,音量在 AudioFileReader 上按音频流设置
InitializeCurrentWavePlayerWithReader(_audioFileReader);
// 开始播放
_wavePlayer.Play();
}
catch
{
DisposeExclusivePlaybackProvider();
if (_audioFileReader != null)
{
_audioFileReader.Dispose();
_audioFileReader = null;
}
DisposeAudioPlayer();
throw;
}
return playbackSessionId;
}
/// <summary>
/// 获取音频文件信息
/// </summary>
/// <param name="filePath">文件路径</param>
/// <returns>文件信息</returns>
public (TimeSpan TotalTime, string Duration) GetAudioFileInfo(string filePath)
{
TryGetAudioFileInfo(filePath, out TimeSpan totalTime, out string duration);
return (totalTime, duration);
}
/// <summary>
/// 读取音频文件时长;返回 false 表示文件无法解码(损坏或格式不支持)。
/// 只开只读的 AudioFileReader,不触碰任何输出设备。
/// </summary>
public bool TryGetAudioFileInfo(string filePath, out TimeSpan totalTime, out string duration)
{
try
{
using (var reader = new AudioFileReader(filePath))
{
totalTime = reader.TotalTime;
duration = TimeFormatHelper.FormatDuration(totalTime);
return true;
}
}
catch
{
totalTime = TimeSpan.Zero;
duration = BroadcastStatuses.UnknownDuration;
return false;
}
}
private static TimeSpan ClampPlaybackTime(TimeSpan value, TimeSpan totalTime)
{
if (value < TimeSpan.Zero)
{
return TimeSpan.Zero;
}
if (totalTime > TimeSpan.Zero && value > totalTime)
{
return totalTime;
}
return value;
}
/// <summary>
/// 暂停当前播放,保留播放器、读取器和独占模式设备锁。
/// </summary>
public void Pause()
{
if (_wavePlayer != null && _wavePlayer.PlaybackState == PlaybackState.Playing)
{
_wavePlayer.Pause();
}
}
/// <summary>
/// 继续当前暂停的播放。
/// </summary>
public void Resume()
{
if (_wavePlayer != null && _wavePlayer.PlaybackState == PlaybackState.Paused)
{
_wavePlayer.Play();
}
}
/// <summary>
/// 定位当前播放位置;独占重采样链路会重建 provider,避免旧缓冲残留。
/// </summary>
public int Seek(TimeSpan position)
{
if (_audioFileReader == null)
{
return _playbackSessionId;
}
TimeSpan clampedPosition = ClampPlaybackTime(position, _audioFileReader.TotalTime);
bool wasPlaying = _wavePlayer != null && _wavePlayer.PlaybackState == PlaybackState.Playing;
bool wasPaused = _wavePlayer != null && _wavePlayer.PlaybackState == PlaybackState.Paused;
if (_outputMode != AudioOutputMode.Exclusive || _exclusivePlaybackProvider == null)
{
_audioFileReader.CurrentTime = clampedPosition;
return _playbackSessionId;
}
string filePath = _audioFileReader.FileName;
float volume = _audioFileReader.Volume;
try
{
if (_wavePlayer != null)
{
if (_wavePlayerPlaybackStoppedHandler != null)
{
// Seek rebuild stops only the old player; unsubscribe first so the new session reports failures normally.
_wavePlayer.PlaybackStopped -= _wavePlayerPlaybackStoppedHandler;
_wavePlayerPlaybackStoppedHandler = null;
}
_wavePlayer.Stop();
}
DisposeAudioPlayer();
DisposeExclusivePlaybackProvider();
_audioFileReader.Dispose();
_audioFileReader = null;
int playbackSessionId = ++_playbackSessionId;
InitializeAudioPlayer(playbackSessionId);
_audioFileReader = new AudioFileReader(filePath)
{
CurrentTime = clampedPosition,
Volume = ClampStreamVolume(volume)
};
InitializeCurrentWavePlayerWithReader(_audioFileReader);
if (wasPlaying || wasPaused)
{
_wavePlayer.Play();
if (wasPaused)
{
_wavePlayer.Pause();
}
}
return _playbackSessionId;
}
catch
{
DisposeExclusivePlaybackProvider();
if (_audioFileReader != null)
{
_audioFileReader.Dispose();
_audioFileReader = null;
}
DisposeAudioPlayer();
throw;
}
}
/// <summary>
/// 停止播放(兼容旧方法名)
/// </summary>
public void Stop()
{
StopPlayback();
}
/// <summary>
/// 停止当前播放
/// </summary>
public void StopPlayback()
{
if (_wavePlayer != null)
{
// 停止播放
_wavePlayer.Stop();
}
DisposeExclusivePlaybackProvider();
if (_audioFileReader != null)
{
// 释放资源
_audioFileReader.Dispose();
_audioFileReader = null;
}
}
/// <summary>
/// 设置音量
/// </summary>
/// <param name="volume">音量(0.0-1.0)</param>
public void SetVolume(float volume)
{
if (_audioFileReader != null)
{
// 只调节当前音频流音量,避免 WASAPI 标准模式改写 Windows 设备主音量
_audioFileReader.Volume = ClampStreamVolume(volume);
}
}
/// <summary>
/// 获取播放状态信息
/// </summary>
/// <param name="currentItem">当前播放项</param>
/// <param name="currentLoopCount">当前循环计数</param>
/// <returns>剩余时间和循环数信息</returns>
public (string RemainingTimeText, string RemainingLoopsText) GetPlaybackStatus(BroadcastItem currentItem, int currentLoopCount)
{
// 默认返回值
string remainingTimeText = "--:--";
string remainingLoopsText = "--";
// 如果有正在播放的项目
if (currentItem != null && _audioFileReader != null && HasActivePlaybackSession)
{
// 计算剩余时间
TimeSpan totalTime = _audioFileReader.TotalTime;
TimeSpan currentTime = _audioFileReader.CurrentTime;
TimeSpan remainingTime = totalTime - currentTime;
// 格式化剩余时间
remainingTimeText = TimeFormatHelper.FormatDuration(remainingTime);
// 计算剩余循环次数
int remainingLoops = currentItem.LoopCount - currentLoopCount;
remainingLoopsText = remainingLoops.ToString();
}
return (remainingTimeText, remainingLoopsText);
}
/// <summary>
/// 释放资源
/// </summary>
public void Dispose()
{
// 停止播放
StopPlayback();
// 释放播放器资源
DisposeAudioPlayer();
}
}
}