Click here to Skip to main content
15,887,683 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.7K   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

 
GeneralHi Pin
Kiya161-Mar-11 7:33
Kiya161-Mar-11 7:33 
Generali want to make it over internet Pin
crysis8928-Feb-11 11:28
crysis8928-Feb-11 11:28 
Generalerror Pin
samathu22-Feb-11 20:11
samathu22-Feb-11 20:11 
Generalerror Pin
samathu21-Feb-11 4:19
samathu21-Feb-11 4:19 
GeneralSome question Pin
Mohammad Reza Valadkhani19-Jan-11 2:27
professionalMohammad Reza Valadkhani19-Jan-11 2:27 
GeneralMy vote of 3 Pin
lxxlxx4-Jan-11 2:09
lxxlxx4-Jan-11 2:09 
GeneralMuLawEncoder Vs ALawEncoder What's the difference Pin
jibin.mn30-Oct-10 0:09
jibin.mn30-Oct-10 0:09 
Generalerrors regarding the project "A Voice Chat Application in C#". Pin
hemendrapsingh28-Feb-10 9:17
hemendrapsingh28-Feb-10 9:17 
I debugged this project it was successful.But when i tried to call a host there were a set of some unsolvable problems by me.
like
1)-only one usage of each socket address(protocol/network address/port)is normally permitted.
2)- the size of datagram is larger than the buffer size.
please tell me what to do to remove these errors...
the code is here:

private void InitializeCall()
{
try
{
udpClient = new UdpClient(8080);

Thread senderThread = new Thread(new ThreadStart(Send));
Thread receiverThread = new Thread(new ThreadStart(Receive));
bIsCallActive = true;
receiverThread.Start();
senderThread.Start();
btnCall.Enabled = false;
btnEndCall.Enabled = true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "VoiceChat-InitializeCall ()", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}

private void SendMessage(Command cmd, EndPoint sendToEP)
{
try
{
Data msgToSend = new Data();

msgToSend.strName = txtName.Text; //Name of the user.
msgToSend.cmdCommand = cmd; //Message to send.
msgToSend.vocoder = vocoder; //Vocoder to be used.

byte[] message = msgToSend.ToByte();

//Send the message asynchronously.
clientSocket.BeginSendTo(message, 0, message.Length, SocketFlags.None, sendToEP, new AsyncCallback(OnSend), null);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "VoiceChat-SendMessage ()", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}

private void VoiceChat_FormClosing(object sender, FormClosingEventArgs e)
{

if (bIsCallActive)
{
UninitializeCall();
DropCall();
}
}
}

//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 send to indicate that call is accepted.
Null, //No command.
}

//Vocoder
enum Vocoder
{
ALaw, //A-Law vocoder.
uLaw, //u-Law vocoder.
None, //Don't use any vocoder.
}

//The data structure by which the server and the client interact with
//each other.
class Data
{
//Default constructor.
public Data()
{
this.cmdCommand = Command.Null;
this.strName = null;
vocoder = Vocoder.ALaw;
}

//Converts the bytes into an object of type Data.
public Data(byte[] data)
{
//The first four bytes are for the Command.
this.cmdCommand = (Command)BitConverter.ToInt32(data, 0);

//The next four store the length of the name.
int nameLen = BitConverter.ToInt32(data, 4);

//This check makes sure that strName has been passed in the array of bytes.
if (nameLen > 0)
this.strName = Encoding.UTF8.GetString(data, 8, nameLen);
else
this.strName = null;
}

//Converts the Data structure into an array of bytes.
public byte[] ToByte()
{
List<byte> result = new List<byte>();

//First four are for the Command.
result.AddRange(BitConverter.GetBytes((int)cmdCommand));

//Add the length of the name.
if (strName != null)
result.AddRange(BitConverter.GetBytes(strName.Length));
else
result.AddRange(BitConverter.GetBytes(0));

//Add the name.
if (strName != null)
result.AddRange(Encoding.UTF8.GetBytes(strName));

return result.ToArray();
}

public string strName; //Name by which the client logs into the room.
public Command cmdCommand; //Command type (login, logout, send message, etc).
public Vocoder vocoder;
}
}
GeneralMy vote of 2 Pin
somireddy25-Feb-10 22:04
somireddy25-Feb-10 22:04 
GeneralCompact Framework Pin
sonia108211-Jan-10 19:20
sonia108211-Jan-10 19:20 
QuestionError while calling on second time [modified] Pin
hiran53612-Oct-09 21:08
hiran53612-Oct-09 21:08 
Generalnot working in studio 2008 Pin
surpatel785-Oct-09 2:21
surpatel785-Oct-09 2:21 
AnswerRe: not working in studio 2008 Pin
Smacky31125-May-10 3:44
Smacky31125-May-10 3:44 
GeneralNotify Pin
mayuwi1-Oct-09 15:12
mayuwi1-Oct-09 15:12 
QuestionHow to select the device dynamically ? Pin
Jack98739-Sep-09 0:23
Jack98739-Sep-09 0:23 
AnswerRe: How to select the device dynamically ? Pin
mayuwi1-Oct-09 13:52
mayuwi1-Oct-09 13:52 
GeneralVoiveChat-InitializeCall() Only one usage of each socket address (protocol/ network address/ port) is nomally permitted Pin
aadiost24-Aug-09 2:49
aadiost24-Aug-09 2:49 
GeneralRe: VoiveChat-InitializeCall() Only one usage of each socket address (protocol/ network address/ port) is nomally permitted Pin
sloaken6-Sep-09 21:18
sloaken6-Sep-09 21:18 
GeneralOnly one usage of each socket address(protocol/network address/port) is normally permitted Pin
goitom219-Aug-09 4:36
goitom219-Aug-09 4:36 
GeneralRe: Only one usage of each socket address(protocol/network address/port) is normally permitted [modified] Pin
sloaken6-Sep-09 9:49
sloaken6-Sep-09 9:49 
GeneralRe: Only one usage of each socket address(protocol/network address/port) is normally permitted Pin
surpatel785-Oct-09 2:48
surpatel785-Oct-09 2:48 
QuestionCan this project be ported for Compact Framework? Pin
m_mughalz18-Aug-09 19:55
m_mughalz18-Aug-09 19:55 
AnswerRe: Can this project be ported for Compact Framework? Pin
jerome51366-Jan-10 10:58
jerome51366-Jan-10 10:58 
QuestionHave you implement on silent detection? Pin
Roathvb2-Aug-09 7:52
Roathvb2-Aug-09 7:52 
GeneralAudio Question Pin
André Baltazar30-Jul-09 4:45
André Baltazar30-Jul-09 4:45 

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.