C # udp-Based p2p voice chat tool

Source: Internet
Author: User

C # udp-Based p2p voice chat tool
Originality declares that the source of this blog post is Ghost. Author of this article original, mailbox zhujunxxxxx@163.com, if you have any questions, please contact the author Overview

Before sent an article http://blog.csdn.net/zhujunxxxxx/article/details/38864817 has been achieved through UDP packet data transmission function, and this article is mainly an application, using udp to send voice and text information.

Voice acquisition

To send voice information, you must first obtain the voice. There are several methods available here. One is to use DirectX's DirectXsound for recording. For ease of use, I use an open-source plug-in NAudio for voice admission. Reference NAudio. dll in the project

 

// ------------------ Recording related audio 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) // maximum 10 s {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); // required = true; // btn_stop.Enabled = false; // required = 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 complete code is recorded and written into the file p2psound_a.wav. 

 

Voice Messaging

After obtaining the voice, we need to send the voice.

After recording the sound, click send. The code for this part is

 

MsgTranslator tran = null; public Form1 () {InitializeComponent (); LoadWasapiDevicesCombo (); // display the audio device Config cfg = SeiClient. getdefaconfig config (); 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 (enter ip); return;} if (t_port.Text =) {MessageBox. show (enter the port number); return;} string ip = t_ip.Text; int port = int. parse (t_port.Text); string nick = t_nick.Text; string msg = voice message; IPEndPoint remote = new IPEndPoint (IPAddress. parse (ip), port); Msg m = new Msg (remote, zz, nick, Command S. 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, the generated voice file is sent out.

 

 

Voice reception and Playback

In fact, the speech reception is no different from the text message reception, but the speech is sent in binary format. Therefore, after receiving the speech, we should write it into a file, after receiving the video, you can play the voice.

The following code stores the received data in a file. This function triggers the event when a message is received in my NetFrame. In the article mentioned earlier

 

Void tran_MessageReceived (object sender, MessageEventArgs e) {Msg msg = e. msg; if (msg. type = Consts. MESSAGE_BINARY) {string m = msg. type +-> + msg. userName + sends 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 +: + msg. normalMsg; AddServerMessage (m );}}

After receiving the voice message, we need to play the video. We still use the plug-in just now to play the video.

 

 

// -------- Play 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 st OppedEventArgs) {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 );}


  <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHA + pgltzybhq9 "" src = "http://www.bkjia.com/uploads/allimg/141021/042Z1O04-1.jpg"/>

The above demonstrates the interface for receiving and sending a voice message.

 

Technical Summary

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

 

I hope this article will provide an idea.

 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.