Click here to Skip to main content
15,888,286 members
Articles / Programming Languages / C#
Article

A Voice Chat Application in C#

Rate me:
Please Sign up or sign in to vote.
4.38/5 (64 votes)
5 Jul 2007CPOL2 min read 717.8K   43K   248   155
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.

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:

C#
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:

C#
//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:

C#
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)


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralNoise Pin
ketansnadar20-Jan-09 18:46
ketansnadar20-Jan-09 18:46 
GeneralRe: Noise Pin
ketansnadar30-Jan-09 18:45
ketansnadar30-Jan-09 18:45 
QuestionMultiCasting Pin
komperpiet5-Jan-09 22:02
komperpiet5-Jan-09 22:02 
AnswerRe: MultiCasting Pin
yesu prakash24-Feb-09 18:25
yesu prakash24-Feb-09 18:25 
GeneralNice One Pin
komperpiet26-Dec-08 17:10
komperpiet26-Dec-08 17:10 
GeneralNo sound Pin
Tyler Helmuth25-Dec-08 8:06
Tyler Helmuth25-Dec-08 8:06 
Generalquestion Pin
shinchan123414-Dec-08 16:37
shinchan123414-Dec-08 16:37 
GeneralRe: question Pin
sloaken6-Sep-09 21:26
sloaken6-Sep-09 21:26 
The nature of UDP is that lost packets are not a problem. Or more precisely, stopping to fix the lost packet is worse than the lost packet. With sound the packets are often small enough that a lost packet here or there is not a problem. And if it is, then you ask the other person to repeat as you did not understand.

Given the following:
"Mary had a little lamb, little lamb"

Which would you prefer:
A: "Mary had li le lamb, litt lamb"

or

B: "Mary had <pause> a li <pause> ttle lamb, litt <pause> le lamb"

Although B has all the sounds the breaking up would be worse since most people can adapt to a missing sound or two.
GeneralHi there.... Pin
Member 441709410-Dec-08 18:48
Member 441709410-Dec-08 18:48 
GeneralRe: Hi there.... Pin
yesu prakash24-Feb-09 18:26
yesu prakash24-Feb-09 18:26 
GeneralConnection Problems Pin
colin_turner9922-Oct-08 0:44
colin_turner9922-Oct-08 0:44 
Generalone way comunication Pin
ravit2316-Aug-08 3:24
ravit2316-Aug-08 3:24 
Questioninternet Pin
BinShao31-Jul-08 20:42
BinShao31-Jul-08 20:42 
QuestionDid you forget to pack/unpack the vocoder type? Pin
Tyler Mc25-Jul-08 22:00
Tyler Mc25-Jul-08 22:00 
QuestionNoise Pin
ppawli17-Jul-08 21:09
ppawli17-Jul-08 21:09 
GeneralProcess Memory Usage Pin
ppawli16-Jul-08 7:34
ppawli16-Jul-08 7:34 
GeneralRe: Process Memory Usage Pin
ppawli16-Jul-08 7:55
ppawli16-Jul-08 7:55 
GeneralG.722 and RTP Pin
Murali Kaundinya17-Jun-08 5:19
professionalMurali Kaundinya17-Jun-08 5:19 
GeneralRe: G.722 and RTP Pin
Hitesh Sharma19-Jun-08 4:54
Hitesh Sharma19-Jun-08 4:54 
GeneralRe: G.722 and RTP Pin
Murali Kaundinya19-Jun-08 7:05
professionalMurali Kaundinya19-Jun-08 7:05 
QuestionAn exixting connection was forcible closed by remote host Pin
vinodnit12-May-08 2:39
vinodnit12-May-08 2:39 
AnswerRe: An exixting connection was forcible closed by remote host Pin
Hitesh Sharma15-May-08 5:40
Hitesh Sharma15-May-08 5:40 
GeneralDirectX Pin
shonaa16-May-08 0:55
shonaa16-May-08 0:55 
GeneralRe: DirectX Pin
vinodnit8-May-08 19:55
vinodnit8-May-08 19:55 
GeneralCross-thread operation not valid: Control 'btnCall' accessed from a thread other then the thread it was created on. Pin
Kashif Abbas13-Mar-08 3:00
Kashif Abbas13-Mar-08 3:00 

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

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.