Click here to Skip to main content
6,821,293 members and growing! (21,315 online)
Email Password   helpLost your password?
Multimedia » Audio and Video » Audio     Intermediate License: The Code Project Open License (CPOL)

A Voice Chat Application in C#

By Hitesh Sharma

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.
C#, Windows, .NET, Visual-Studio, Dev
Posted:5 Jul 2007
Views:102,875
Bookmarked:134 times
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
17 votes for this article.
Popularity: 4.52 Rating: 3.68 out of 5
1 vote, 5.9%
1
2 votes, 11.8%
2
1 vote, 5.9%
3
2 votes, 11.8%
4
11 votes, 64.7%
5

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


Member

Location: United States United States

Other popular Audio and Video articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 25 of 99 (Total in Forum: 99) (Refresh)FirstPrevNext
QuestionI need a conference chat PinmemberAtanov17:24 26 Jan '10  
GeneralCompact Framework Pinmembersonia108220:20 11 Jan '10  
QuestionError while calling on second time [modified] Pinmemberhiran53622:08 12 Oct '09  
Generalnot working in studio 2008 Pinmembersurpatel783:21 5 Oct '09  
GeneralNotify Pinmembermayuwi16:12 1 Oct '09  
GeneralHow to select the device dynamically ? PinmemberJack98731:23 9 Sep '09  
GeneralRe: How to select the device dynamically ? Pinmembermayuwi14:52 1 Oct '09  
GeneralVoiveChat-InitializeCall() Only one usage of each socket address (protocol/ network address/ port) is nomally permitted Pinmemberaadiost3:49 24 Aug '09  
GeneralRe: VoiveChat-InitializeCall() Only one usage of each socket address (protocol/ network address/ port) is nomally permitted Pinmembersloaken22:18 6 Sep '09  
GeneralOnly one usage of each socket address(protocol/network address/port) is normally permitted Pinmembergoitom25:36 19 Aug '09  
GeneralRe: Only one usage of each socket address(protocol/network address/port) is normally permitted [modified] Pinmembersloaken10:49 6 Sep '09  
GeneralRe: Only one usage of each socket address(protocol/network address/port) is normally permitted Pinmembersurpatel783:48 5 Oct '09  
GeneralCan this project be ported for Compact Framework? Pinmemberm_mughalz20:55 18 Aug '09  
GeneralRe: Can this project be ported for Compact Framework? Pinmemberjerome513611:58 6 Jan '10  
QuestionHave you implement on silent detection? PinmemberRoathvb8:52 2 Aug '09  
GeneralAudio Question PinmemberAndré Baltazar5:45 30 Jul '09  
GeneralCan i contact you? Pinmemberdonperry13:23 20 Jun '09  
GeneralRe: Can i contact you? PinmemberHitesh Sharma8:41 21 Jul '09  
Generalcross-thered operation not valid exeption Pinmemberkumeneger17:49 3 Jun '09  
QuestionHow to use it on internet? PinmemberNitin Jenekar4:16 14 Apr '09  
GeneralHow to use this application in wide are networks (WAN) networks Pinmemberchandrababu0921:26 22 Feb '09  
Question[Message Deleted] Pinmemberzeeshanpatoli18:58 21 Feb '09  
AnswerRe: when i Minimize the window sound is lost PinmemberChrisRRRR5:27 3 Mar '09  
Generalone way of communication is working .. Pinmemberchandrababu0919:55 17 Feb '09  
GeneralCross-thread operation not valid exception Pinmemberchandrababu091:40 13 Feb '09  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

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

PermaLink | Privacy | Terms of Use
Last Updated: 5 Jul 2007
Editor: Genevieve Sovereign
Copyright 2007 by Hitesh Sharma
Everything else Copyright © CodeProject, 1999-2010
Web21 | Advertise on the Code Project