C# 實現語音聊天

yswenli發表於2021-02-01

一、語音聊天說專業點就是即時語音,是一種基於網路的快速傳遞語音資訊的技術,普遍應用於各類社交軟體中,優勢主要有以下幾點:

(1)時效性:視訊直播會因為頻寬問題有時出現延遲高的問題,而語音直播相對來說會好很多,延遲低,並且能夠第·一時間與聽眾互動,時效性強。

(2)隱私性:這一點體現在何處,如主播不想暴露自己的長相,或者進行問題回答是,沒有視訊的話會讓主播感到更安心,所以語音直播隱私性更強。

(3)內容質量高:因為語音直播不靠“顏值”只有好的內容才能夠吸引使用者,所以語音直播相對來說內容質量更高。

(4)成本降低:語音直播相對視訊直播來說,頻寬流量等都會便宜許多,成本降低不少,更加實惠。

二、語音聊天主要步驟:音訊採集、壓縮編碼、網路傳輸、解碼還原、播放音訊,如下圖所示

 

 下面就從程式碼的角度來詳說一下這幾個步驟。

(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)音訊資料壓縮編碼,常見壓縮格式比較多,例如mp3、acc、speex等,這裡以speex為例

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();

三、測試執行,通過分析語音聊天的幾個關鍵問題點後,按步驟封裝好程式碼,接下來就是用例項來測試一下效果了。

客戶端封裝在按鈕事件中:

 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
如果發現本文有什麼問題和任何建議,也隨時歡迎交流~

 

相關文章