Click here to Skip to main content
Click here to Skip to main content

A Voice Chat Application in C#

By , 5 Jul 2007
 

Screenshot - VoiceChat.jpg

Introduction

In this article, I will discuss a simple voice chat application. We will grab the audio from the microphone using DirectSound and transmit it in UDP packets. To make things interesting, I used G711 vocoder to compress the data before transmission. I won't discuss here how to capture the audio from microphone and play it back using DirectSound or how G711 is implemented. For all these things you can look into the references given at the end of this article. Before we go further, let's discuss the architecture of the application. We will use the following call messages between the parties.

|             Invite                | 

| --------------------------------> |

|               OK                  |

| <-------------------------------- |

|                                   |

| --------------------------------> |

|            Audio flow             |

| <-------------------------------- |

|               Bye                 | 

| --------------------------------> |

A                                   B

Using the code

Here are the commands for interaction between the two parties:

enum Command
{
    Invite, //Make a call.
    Bye,    //End a call.
    Busy,   //User busy.
    OK,     //Response to an invite message. OK is sent to 
            //indicate that call is accepted.
    Null,   //No command.
}

When the user wants to make a call, we send an Invite message and wait for an OK response. When we receive an OK, we start receiving/sending audio captured from the microphone. If the remote party rejects the call then a Busy response is sent. To drop a call, we simply send a Bye message. The application will asynchronously receive/send call messages on port 1450 and synchronously receive/send audio data on port 1550. In other words, the application listens on two ports: one for call messages and the other for audio data. I will now walk you through some code. When the application starts, we start listening for call messages on port 1450:

//Using UDP sockets
clientSocket = new Socket(AddressFamily.InterNetwork, 
    SocketType.Dgram, 
    ProtocolType.Udp);
EndPoint ourEP = new IPEndPoint(IPAddress.Any, 1450);

//Listen asynchronously on port 1450 for 
//coming messages (Invite, Bye, etc).
clientSocket.Bind(ourEP);

//Receive data from any IP.
EndPoint remoteEP = (EndPoint)(new IPEndPoint(IPAddress.Any, 0));
byteData = new byte[1024];

//Receive data asynchornously.
clientSocket.BeginReceiveFrom(byteData,
    0, byteData.Length,
    SocketFlags.None,
    ref remoteEP,
    new AsyncCallback(OnReceive),
    null);

When we receive a message, we process it to see what type of message it is and act accordingly. Please see the OnReceive handler for it in the attached project files. To receive/send audio from a microphone, we start two threads so that the synchronous send/receive doesn't block our UI. This is done as follows, noting that the audio is received/sent on port 1550:

private void InitializeCall()
{
    try
    {
        //Start listening on port 1500.
        udpClient = new UdpClient(1550);
        Thread senderThread = new Thread(new ThreadStart(Send));
        Thread receiverThread = new Thread(new ThreadStart(Receive));
        bIsCallActive = true;

        //Start the receiver and sender thread.
        receiverThread.Start();
        senderThread.Start();
        btnCall.Enabled = false;
        btnEndCall.Enabled = true;
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, 
            "VoiceChat-InitializeCall ()", MessageBoxButtons.OK, 
        MessageBoxIcon.Error);
    }
}

The Send and Receive methods can be seen in the attached project; understanding them is easy.

References

History

  • 5 July, 2007 -- Original version posted

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Hitesh Sharma

United States United States
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionDirectX ProblemmemberMember 1006022322-May-13 7:37 
AnswerRe: DirectX ProblemmemberAletheuein3-Jun-13 2:17 
QuestionIs it possible to voice call to remote desktop using this code?memberrajesh@198910-Apr-13 3:17 
Questionmo me so rotto il cazzomemberCrisLoveStefy1-Sep-12 22:23 
QuestionzxxczcZCZCmembersaravanan33323-Aug-12 19:48 
Questionfor allmemberkumeneger11-May-12 3:06 
BugProblem!memberJrPacheco17-Apr-12 3:59 
Questiononly one usage of each socket address (protocol/network address/port) is normally permittedmemberMember 84226775-Apr-12 1:34 
Questionis it possible to encrypt a voice in your application?memberThendral.N27-Mar-12 1:02 
QuestionVoice chat application doesnt connect with another machinememberThendral.N24-Jan-12 1:00 
Questiononly one usage of each socket address protocol network address port is normally permittedmemberThendral.N23-Jan-12 23:19 
QuestionSend message issuememberdanm3612-Jan-12 10:12 
Questionhi sir how can I add Microsoft.directx and Microsoft.directx .DirectSound and voicechat.vhost.exe.manifest refferance files tell me plz [modified]memberbahidab4-Jan-12 0:17 
QuestionQuerry..memberTarun Khatana14-Dec-11 8:45 
Generalno sound while lost focusmemberAkeeq14-Jun-11 1:39 
GeneralRe: no sound while lost focusmemberAkeeq16-Jun-11 20:40 
GeneralRe: no sound while lost focusmemberharshad3654-Dec-12 17:43 
GeneralRe: no sound while lost focusmemberAkeeq11-Dec-12 0:52 
GeneralSound QualitymemberOblivion1707-Jun-11 5:51 
GeneralRe: Sound Qualitymemberbubifengyun7-Jan-13 16:36 
Questionhimembermaktumpashal22-May-11 2:15 
GeneralMDA LoaderLock Error; Error in ApplicationmemberAkeeq13-May-11 19:36 
GeneralRe: MDA LoaderLock Error; Error in ApplicationmemberAkeeq16-Jun-11 20:44 
GeneralMy vote of 5memberMember 446500731-Mar-11 14:29 
GeneralHimemberKiya161-Mar-11 7:33 
Generali want to make it over internetmembercrysis8928-Feb-11 11:28 
Generalerrormembersamathu22-Feb-11 20:11 
Generalerrormembersamathu21-Feb-11 4:19 
GeneralSome questionmemberRezabest19-Jan-11 2:27 
GeneralMy vote of 3memberlxxlxx4-Jan-11 2:09 
GeneralMuLawEncoder Vs ALawEncoder What's the differencememberjibin.mn30-Oct-10 0:09 
Generalerrors regarding the project "A Voice Chat Application in C#".memberhemendrapsingh28-Feb-10 9:17 
GeneralMy vote of 2membersomireddy25-Feb-10 22:04 
GeneralCompact Frameworkmembersonia108211-Jan-10 19:20 
QuestionError while calling on second time [modified]memberhiran53612-Oct-09 21:08 
Generalnot working in studio 2008membersurpatel785-Oct-09 2:21 
AnswerRe: not working in studio 2008memberSmacky31125-May-10 3:44 
GeneralNotifymembermayuwi1-Oct-09 15:12 
QuestionHow to select the device dynamically ?memberJack98739-Sep-09 0:23 
AnswerRe: How to select the device dynamically ?membermayuwi1-Oct-09 13:52 
GeneralVoiveChat-InitializeCall() Only one usage of each socket address (protocol/ network address/ port) is nomally permittedmemberaadiost24-Aug-09 2:49 
GeneralRe: VoiveChat-InitializeCall() Only one usage of each socket address (protocol/ network address/ port) is nomally permittedmembersloaken6-Sep-09 21:18 
GeneralOnly one usage of each socket address(protocol/network address/port) is normally permittedmembergoitom219-Aug-09 4:36 
GeneralRe: Only one usage of each socket address(protocol/network address/port) is normally permitted [modified]membersloaken6-Sep-09 9:49 
GeneralRe: Only one usage of each socket address(protocol/network address/port) is normally permittedmembersurpatel785-Oct-09 2:48 
QuestionCan this project be ported for Compact Framework?memberm_mughalz18-Aug-09 19:55 
AnswerRe: Can this project be ported for Compact Framework?memberjerome51366-Jan-10 10:58 
QuestionHave you implement on silent detection?memberRoathvb2-Aug-09 7:52 
GeneralAudio QuestionmemberAndré Baltazar30-Jul-09 4:45 
QuestionCan i contact you?memberdonperry20-Jun-09 12:23 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130617.1 | Last Updated 5 Jul 2007
Article Copyright 2007 by Hitesh Sharma
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid