恢復內容開始 PCM音頻網路流播放,至於用處,就不多解釋了。 一個簡單的類,基於NAudio,一個簡單的拼裝類,實例化時三個參數,依次是採樣率,系統播放設備Index,播放聲道,調用PlayData方法傳入PCM的音頻流即可,有流就傳進去,數據斷了,播放自動停。 接下來把代碼貼出來: 1 publi ...
---恢復內容開始---
PCM音頻網路流播放,至於用處,就不多解釋了。
一個簡單的類,基於NAudio,一個簡單的拼裝類,實例化時三個參數,依次是採樣率,系統播放設備Index,播放聲道,調用PlayData方法傳入PCM的音頻流即可,有流就傳進去,數據斷了,播放自動停。
接下來把代碼貼出來:
1 public class PCMPlayer 2 { 3 private MonoToStereoProvider16 monoToStereoProvider16; 4 private BufferedWaveProvider bufferedWaveProvider; 5 private WaveOut waveOut; 6 private bool isRunning = false; 7 private PCMPlayerChannel currentChannel; 8 9 /// <summary> 10 /// 11 /// </summary> 12 /// <param name="sampleRate">採樣率8K至64K</param> 13 /// <param name="deviceNumber">通過GetPlayDevices來獲取字典的KEY值</param> 14 /// <param name="playerChannel">初始化時播放的聲道</param> 15 public PCMPlayer(int sampleRate, int deviceNumber = 0, PCMPlayerChannel playerChannel = PCMPlayerChannel.Both) 16 { 17 currentChannel = playerChannel; 18 WaveFormat = new WaveFormat(sampleRate, 16, 1); 19 bufferedWaveProvider = new BufferedWaveProvider(WaveFormat); 20 monoToStereoProvider16 = new MonoToStereoProvider16(bufferedWaveProvider); 21 waveOut = new WaveOut(); 22 waveOut.DeviceNumber = deviceNumber; 23 waveOut.Init(monoToStereoProvider16); 24 waveOut.Play(); 25 isRunning = true; 26 } 27 28 public void PlayData(byte[] data) 29 { 30 if (!isRunning) return; 31 bufferedWaveProvider.AddSamples(data, 0, data.Length); 32 } 33 34 public void ClosePlay() 35 { 36 isRunning = false; 37 waveOut.Stop(); 38 waveOut.Dispose(); 39 } 40 41 public bool SetPlayChannel(PCMPlayerChannel playerChannel) 42 { 43 if (!isRunning || waveOut == null || monoToStereoProvider16 == null) return false; 44 switch (playerChannel) 45 { 46 case PCMPlayerChannel.Left: 47 { 48 monoToStereoProvider16.LeftVolume = 1.0f; 49 monoToStereoProvider16.RightVolume = 0.0f; 50 } 51 break; 52 case PCMPlayerChannel.Right: 53 { 54 monoToStereoProvider16.LeftVolume = 0.0f; 55 monoToStereoProvider16.RightVolume = 1.0f; 56 } 57 break; 58 case PCMPlayerChannel.Both: 59 { 60 monoToStereoProvider16.LeftVolume = 1.0f; 61 monoToStereoProvider16.RightVolume = 1.0f; 62 } 63 break; 64 default: return false; 65 } 66 return true; 67 } 68 69 public WaveFormat WaveFormat { get; private set; } 70 71 public static Dictionary<int, WaveOutCapabilities> GetPlayDevices 72 { 73 get 74 { 75 Dictionary<int, WaveOutCapabilities> result = new Dictionary<int, WaveOutCapabilities>(); 76 try 77 { 78 int count = WaveOut.DeviceCount; 79 for (int i = 0; i < count; i++) 80 { 81 var item = WaveOut.GetCapabilities(i); 82 result.Add(i, item); 83 } 84 } 85 catch { } 86 return result; 87 } 88 } 89 } 90 91 public enum PCMPlayerChannel 92 { 93 Left, 94 Right, 95 Both 96 }View Code
預告:下一篇簡單講一下音頻流網路傳輸時壓縮與解壓(基於NSpeex的音頻10倍壓縮,肉耳聽不出損耗)