1、語音聊天說專業點就是即時語音,是一種基於網絡的快速傳遞語音信息的技術,廣泛應用於各種社交軟件中,優點主要有如下幾點:html
(1)時效性:視頻直播會由於帶寬問題有時出現延遲高的問題,而語音直播相對來講會好不少,延遲低,而且可以第·一時間與聽衆互動,時效性強。git
(2)隱私性:這一點體如今何處,如主播不想暴露本身的長相,或者進行問題回答是,沒有視頻的話會讓主播感到更安心,因此語音直播隱私性更強。github
(3)內容質量高:由於語音直播不靠「顏值」只有好的內容纔可以吸引用戶,因此語音直播相對來講內容質量更高。服務器
(4)成本下降:語音直播相對視頻直播來講,帶寬流量等都會便宜許多,成本下降很多,更加實惠。網絡
2、語音聊天主要步驟:音頻採集、壓縮編碼、網絡傳輸、解碼還原、播放音頻,以下圖所示ide
下面就從代碼的角度來詳說一下這幾個步驟。函數
(1)音頻採集,讀取麥克風設備數據測試
1 private readonly WaveIn _waveIn; 2 _waveIn = new WaveIn(); 3 _waveIn.BufferMilliseconds = 50; 4 _waveIn.DeviceNumber = 0; 5 _waveIn.DataAvailable += OnAudioCaptured; 6 _waveIn.StartRecording();
(2)音頻數據壓縮編碼,常見壓縮格式比較多,例如mp三、acc、speex等,這裏以speex爲例ui
1 private readonly WideBandSpeexCodec _speexCodec; 2 _speexCodec = new WideBandSpeexCodec(); 3 _waveIn.WaveFormat = _speexCodec.RecordFormat; 4 5 void OnAudioCaptured(object sender, WaveInEventArgs e) 6 { 7 byte[] encoded = _speexCodec.Encode(e.Buffer, 0, e.BytesRecorded); 8 _audioClient.Send(encoded); 9 }
(3)網絡傳輸,爲了保證即時傳輸udp協議有着自然的優勢編碼
1 using SAEA.Sockets; 2 using SAEA.Sockets.Base; 3 using SAEA.Sockets.Model; 4 using System; 5 using System.Net; 6 7 namespace GFF.Component.GAudio.Net 8 { 9 public class AudioClient 10 { 11 IClientSocket _udpClient; 12 13 BaseUnpacker _baseUnpacker; 14 15 public event Action<Byte[]> OnReceive; 16 17 public AudioClient(IPEndPoint endPoint) 18 { 19 var bContext = new BaseContext(); 20 21 _udpClient = SocketFactory.CreateClientSocket(SocketOptionBuilder.Instance.SetSocket(SAEASocketType.Udp) 22 .SetIPEndPoint(endPoint) 23 .UseIocp(bContext) 24 .SetReadBufferSize(SocketOption.UDPMaxLength) 25 .SetWriteBufferSize(SocketOption.UDPMaxLength) 26 .Build()); 27 28 _baseUnpacker = (BaseUnpacker)bContext.Unpacker; 29 30 _udpClient.OnReceive += _udpClient_OnReceive; 31 } 32 33 private void _udpClient_OnReceive(byte[] data) 34 { 35 OnReceive?.Invoke(data); 36 } 37 38 public void Connect() 39 { 40 _udpClient.Connect(); 41 } 42 43 public void Send(byte[] data) 44 { 45 _udpClient.SendAsync(data); 46 } 47 48 public void Disconnect() 49 { 50 _udpClient.Disconnect(); 51 } 52 53 } 54 }
(4)服務器轉發,客戶端使用udp,服務器這裏一樣也使用udp來轉發
1 using SAEA.Sockets; 2 using SAEA.Sockets.Base; 3 using SAEA.Sockets.Interface; 4 using SAEA.Sockets.Model; 5 using System; 6 using System.Collections.Concurrent; 7 using System.Net; 8 using System.Threading.Tasks; 9 10 namespace GFF.Component.GAudio.Net 11 { 12 public class AudioServer 13 { 14 IServerSocket _udpServer; 15 16 ConcurrentDictionary<string, IUserToken> _cache; 17 18 public AudioServer(IPEndPoint endPoint) 19 { 20 _cache = new ConcurrentDictionary<string, IUserToken>(); 21 22 _udpServer = SocketFactory.CreateServerSocket(SocketOptionBuilder.Instance.SetSocket(SAEASocketType.Udp) 23 .SetIPEndPoint(endPoint) 24 .UseIocp<BaseContext>() 25 .SetReadBufferSize(SocketOption.UDPMaxLength) 26 .SetWriteBufferSize(SocketOption.UDPMaxLength) 27 .SetTimeOut(5000) 28 .Build()); 29 _udpServer.OnAccepted += _udpServer_OnAccepted; 30 _udpServer.OnDisconnected += _udpServer_OnDisconnected; 31 _udpServer.OnReceive += _udpServer_OnReceive; 32 } 33 34 public void Start() 35 { 36 _udpServer.Start(); 37 } 38 39 public void Stop() 40 { 41 _udpServer.Stop(); 42 } 43 44 private void _udpServer_OnReceive(ISession currentSession, byte[] data) 45 { 46 Parallel.ForEach(_cache.Keys, (id) => 47 { 48 try 49 { 50 _udpServer.SendAsync(id, data); 51 } 52 catch { } 53 }); 54 } 55 56 private void _udpServer_OnAccepted(object obj) 57 { 58 var ut = (IUserToken)obj; 59 if (ut != null) 60 { 61 _cache.TryAdd(ut.ID, ut); 62 } 63 } 64 65 private void _udpServer_OnDisconnected(string ID, Exception ex) 66 { 67 _cache.TryRemove(ID, out IUserToken _); 68 } 69 } 70 }
(5)解碼還原,客戶端將從服務器收到的數據按約定的壓縮格式,進行解壓縮還原成音頻數據
1 private readonly BufferedWaveProvider _waveProvider; 2 _waveProvider = new BufferedWaveProvider(_speexCodec.RecordFormat); 3 4 private void _audioClient_OnReceive(byte[] data) 5 { 6 byte[] decoded = _speexCodec.Decode(data, 0, data.Length); 7 _waveProvider.AddSamples(decoded, 0, decoded.Length); 8 }
(6)播放音頻,使用播放設備來播放解碼後的音頻數據
1 private readonly IWavePlayer _waveOut; 2 _waveOut = new WaveOut(); 3 _waveOut.Init(_waveProvider); 4 _waveOut.Play();
3、測試運行,經過分析語音聊天的幾個關鍵問題點後,按步驟封裝好代碼,接下來就是用實例來測試一下效果了。
客戶端封裝在按鈕事件中:
1 GAudioClient _gAudioClient = null; 2 3 private void toolStripDropDownButton2_ButtonClick(object sender, EventArgs e) 4 { 5 if (_gAudioClient == null) 6 { 7 ClientConfig clientConfig = ClientConfig.Instance(); 8 _gAudioClient = new GAudioClient(clientConfig.IP, clientConfig.Port + 2); 9 _gAudioClient.Start(); 10 } 11 else 12 { 13 _gAudioClient.Dispose(); 14 _gAudioClient = null; 15 } 16 }
服務端封裝在main函數中:
1 ConsoleHelper.WriteLine("正在初始化語音服務器...", ConsoleColor.DarkBlue); 2 _gAudioServer = new GAudioServer(filePort + 1); 3 ConsoleHelper.WriteLine("語音服務器初始化完畢...", ConsoleColor.DarkBlue); 4 ConsoleHelper.WriteLine("正在啓動語音服務器...", ConsoleColor.DarkBlue); 5 _gAudioServer.Start(); 6 ConsoleHelper.WriteLine("語音服務器初始化完畢", ConsoleColor.DarkBlue);
萬事俱備,如今F5跑起來試試。
如上紅框所示,喊了幾句至關於Hello World的Hello沒有問題,大功初步告成~
轉載請標明本文來源:https://www.cnblogs.com/yswenli/p/14353482.html
更多內容歡迎個人的github:https://github.com/yswenli/GFF若是發現本文有什麼問題和任何建議,也隨時歡迎交流~