Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

C# P2P Voice chat tool based on UDP

2025-01-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

Today, I will talk to you about C# P2P voice chat tools based on UDP, which may not be well understood by many people. in order to make you understand better, the editor has summarized the following content for you. I hope you can get something according to this article.

It is mainly an application that uses udp to transmit information such as voice and text. In this system, there are no servers and clients, and the communication between them is directly related to each other. It can achieve good results.

Voice acquisition

If you want to send a voice message, you have to get the voice first. Here are several ways. One is to use DirectX's DirectXsound to record. I want to easily use an open source plug-in, NAudio, to achieve voice admission. Reference NAudio.dll in a project

/ /-recording related-- private IWaveIn waveIn; private WaveFileWriter writer; private void LoadWasapiDevicesCombo () {var deviceEnum = new MMDeviceEnumerator (); var devices = deviceEnum.EnumerateAudioEndPoints (DataFlow.Capture, DeviceState.Active) .ToList () ComboBox1.DataSource = devices; comboBox1.DisplayMember = "FriendlyName";} private void CreateWaveInDevice () {waveIn = new WaveIn (); waveIn.WaveFormat = new WaveFormat (8000, 1); waveIn.DataAvailable + = OnDataAvailable; waveIn.RecordingStopped + = OnRecordingStopped } void OnDataAvailable (object sender, WaveInEventArgs e) {if (this.InvokeRequired) {this.BeginInvoke (new EventHandler (OnDataAvailable), sender, e);} else {writer.Write (e.Buffer, 0, e.BytesRecorded) Int secondsRecorded = (int) (writer.Length / writer.WaveFormat.AverageBytesPerSecond); if (secondsRecorded > = 10) / / * 10s {StopRecord ();} else {l_sound.Text = secondsRecorded + "s" } void OnRecordingStopped (object sender, StoppedEventArgs e) {if (InvokeRequired) {BeginInvoke (new EventHandler (OnRecordingStopped), sender, e);} else {FinalizeWaveFile () }} void StopRecord () {AllChangeBtn (btn_luyin, true); AllChangeBtn (btn_stop, false); AllChangeBtn (btn_sendsound, true); AllChangeBtn (btn_play, true); / / btn_luyin.Enabled = true; / / btn_stop.Enabled = false / / btn_sendsound.Enabled = true; / / btn_play.Enabled = true; if (waveIn! = null) waveIn.StopRecording (); / / Cleanup ();} private void Cleanup () {if (waveIn! = null) {waveIn.Dispose () WaveIn = null;} FinalizeWaveFile ();} private void FinalizeWaveFile () {if (writer! = null) {writer.Dispose (); writer = null }} / / start recording private void btn_luyin_Click (object sender, EventArgs e) {btn_stop.Enabled = true; btn_luyin.Enabled = false; if (waveIn = = null) {CreateWaveInDevice () } if (File.Exists (soundfile)) {File.Delete (soundfile);} writer = new WaveFileWriter (soundfile, waveIn.WaveFormat); waveIn.StartRecording ();}

The above code implements the recording and writes to the file p2psound_A.wav

Voice transmission

After we get the voice, we need to send it out.

When we have recorded the sound and click send, this part of the related code is

MsgTranslator tran = null; ublic Form1 () {InitializeComponent (); LoadWasapiDevicesCombo (); / / display audio device Config cfg = SeiClient.GetDefaultConfig (); cfg.Port = 7777; UDPThread udp = new UDPThread (cfg); tran = new MsgTranslator (udp, cfg); tran.MessageReceived + = tran_MessageReceived; tran.Debuged + = new EventHandler (tran_Debuged) } private void btn_sendsound_Click (object sender, EventArgs e) {if (t_ip.Text = = "") {MessageBox.Show ("Please enter ip"); return;} if (t_port.Text = = "") {MessageBox.Show ("Please enter port number") Return;} string ip = tweeip.Text; int port = int.Parse (t_port.Text); string nick = tweenick.Text; string msg = "voice message"; IPEndPoint remote = new IPEndPoint (IPAddress.Parse (ip), port) Msg m = new Msg (remote, "zz", nick, Commands.SendMsg, msg, "Come From A"); m.IsRequireReceive = true; m.ExtendMessageBytes = FileContent (soundfile); m.PackageNo = Msg.GetRandomNumber (); m.Type = Consts.MESSAGE_BINARY; tran.Send (m) } private byte [] FileContent (string fileName) {FileStream fs = new FileStream (fileName, FileMode.Open, FileAccess.Read); try {byte [] buffur = new byte [fs.Length]; fs.Read (buffur, 0, (int) fs.Length); return buffur } catch (Exception ex) {return null;} finally {if (fs! = null) {/ / close resource fs.Close () }

In this way, we sent out the resulting voice file.

Reception and playback of voice

In fact, the reception of voice is no different from that of text message, except that when the voice is sent, it is sent in binary, so we should write it into a file after receiving the voice, and when the reception is complete, just play the voice.

The following code is mainly to save the received data to a file. This function is the event triggered when a message is received in my NetFrame, in the article mentioned earlier in the article.

Void tran_MessageReceived (object sender, MessageEventArgs e) {Msg msg = e.msg; if (msg.Type = = Consts.MESSAGE_BINARY) {string m = msg.Type + "- >" + msg.UserName + "send a binary message!"; AddServerMessage (m) If (File.Exists (recive_soundfile)) {File.Delete (recive_soundfile);} FileStream fs = new FileStream (recive_soundfile, FileMode.Create, FileAccess.Write); fs.Write (msg.ExtendMessageBytes, 0, msg.ExtendMessageBytes.Length); fs.Close () / / play_sound (recive_soundfile); ChangeBtn (true);} else {string m = msg.Type + "- >" + msg.UserName + "say:" + msg.NormalMsg; AddServerMessage (m);}}

After receiving the voice message, we want to play it, and we still use the plug-in to play it.

/ /-playback part-private IWavePlayer wavePlayer; private WaveStream reader; public void play_sound (string filename) {if (wavePlayer! = null) {wavePlayer.Dispose (); wavePlayer = null } if (reader! = null) {reader.Dispose ();} reader = new MediaFoundationReader (filename, new MediaFoundationReader.MediaFoundationReaderSettings () {SingleReaderObject = true}); if (wavePlayer = = null) {wavePlayer = new WaveOut (); wavePlayer.PlaybackStopped + = WavePlayerOnPlaybackStopped WavePlayer.Init (reader);} wavePlayer.Play ();} private void WavePlayerOnPlaybackStopped (object sender, StoppedEventArgs stoppedEventArgs) {if (stoppedEventArgs.Exception! = null) {MessageBox.Show (stoppedEventArgs.Exception.Message) } if (wavePlayer! = null) {wavePlayer.Stop ();} btn_luyin.Enabled = true;} private void btn_play_Click (object sender, EventArgs e) {btn_luyin.Enabled = false; play_sound (soundfile);}

The interface for receiving and sending a voice message is demonstrated above.

Technical summary

The main technologies used are the recording and playback functions of UDP and NAudio.

After reading the above, do you have any further understanding of the P2P voice chat tool implemented by C# based on UDP? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report