High performance VoIP SDK for .Net developers

VoIP SIP SDK

How to make a Voice Call (and play a wav) with Ozeki VoIP SIP SDK

Explanation

Prerequisities

Download: SoftphoneExample.zip

This article contains the main concepts of making a voice call with your softphone and how to program the feature of playing a .wav audio file using the support of the Ozeki VoIP SIP SDK. After reading this material, you will be capable of writing your own methods for these purposes in your softphone application.

Introduction

When talking about communication the first thing we think of is voice chat. The primary goal of software phones is to make voice calls through the Internet (Figure 1). You will find all information for programming this essential function on this page.

Figure 2 shows the time sequence of calls that occur during the establishment of a call. The three participants of the call is the caller, the VoIP PBX and the softphone that is called party.


Figure 1 - Voice calls are essential parts of communication through the Internet

At first, the caller that is Ozeki VoIP SIP SDK in Figure 2 sends an INVITE message to the PBX. The PBX sends back a message that informs the caller about the PBX trying to establish a line between the caller and the remote softphone (message code 100) and at the same time it sends an INVITE message to the softphone.

The called softphone sends back an info message about trying to establish the connection and if the line has been established, it sends a Ringing message back to the PBX. The ringing message (message code 180) is also returned to the caller SDK from the PBX.

When the called softphone answers the call (presses the Pick Up button), an OK message (message code 200) is sent to the PBX and it is forwarded from the PBX to the caller.

At this point the PBX gets out of the connection, and the caller sends an acknowledge message (ACK) to the softphone directly to inform is about the established call. After this the two remote contacts can finally talk to each other.


Figure 2 - SIP Invite UML sequence diagram

After reading this article, you will be familiar with all the information needed to write the right methods for voice calls. As Ozeki VoIP SIP SDK grants a great support for softphone applications, you will find it really easy to program this function.

This material is based on the support Ozeki VoIP SIP SDK provides, so you will need to have the SDK to be able to follow the guide. You will also need Visual Studio and some basic C# programming skills to understand the following paragraphs.

This page only covers the methods related to voice calling and playing a .wav file, but if you are interested in the basics of softphone programming or registering your softphone to a PBX using Ozeki VoIP SIP SDK, you can check the following sites:

This manual assumes that you already have a sample softphone application GUI, you have registered your Ozeki VoIP SIP SDK to your Visual Studio project and you wrote the necessary methods for registering the softphone to the SIP PBX using the information you got from your PBX provider.

Now, it is time to write some basic methods that handle the voice call and .wav playing. For this purpose, you will need to expand your softphone GUI with some new elements and to write some EventHandler methods, but with Ozeki VoIP SIP SDK support, they will be a piece of cake.

How to define an event handler

Let's see how your simple softphone GUI looks like now. You have the essential function buttons (Pick up and Hang up), the numeric keypad (including * and # buttons) and a textbox for getting the notifications from the softphone (Figure 3).


Figure 3 - A simple softphone GUI only contains some essential features

First you need to write the calling methods and after that you can expand the GUI for support of the .wav playing.

For initiating a phone call, you will need to be able to dial with your keypad. This article does not contain the methods that make your keypad work, but you can find them if you visit the Ozeki VoIP SIP Softphone page.

This page will show you how to write the essential methods for starting and ending voice calls with your Ozeki VoIP SIP SDK supported softphone.
Starting a voice call should be made with pressing the Pick Up button, so you have to write the EventHandler method for the default event of the button that is Click.

The EventHandler method is created by the Visual Studio if you double click on the button of Design tab. You can rename this method if you don't like the generated name of it.

In Code 1 you can see the header of the EventHandler method that was renamed to buttonPickUp_Click. It is a standard EventHandler with two parameters to identify the source of the event that is the sender and the information about the event's environment that is stored in the second parameter.

The method is private as it is only called from your softphone application when the Pick Up button is pressed.

private void buttonPickUp_Click(object sender, EventArgs e)

Code 1 - The EventHandler method of the Pick Up button has a standard header

As the Pick Up button has multiple functionalities, the EventHandler method contains some conditional instructions. These check if you want to answer an incoming call or to initiate a voice call yourself.

First you need to initialize a call object

Code 2 shows the first instruction that runs when you want to start a call with your softphone. As Ozeki VoIP SIP SDK has a great implementation for the exact calling method, you only have to use the provided methods to initiate a call.

The code segment initializes the call object that is defined as an IPhoneCall instance. This object type is provided by the Ozeki VoIP SIP SDK. The call needs a phoneLine object and the calling information (phone number) from the textBox object on the main form.

call = softPhone.CreateCallObject(phoneLine, textBox1.Text);

Code 2 - Ozeki VoIP SIP SDK provides the method to create a call object

You have surely realized by now that working with Ozeki VoIP SIP SDK makes your programming work really easy. There are some more method calls to make and your softphone will be perfectly capable for voice calls.

You will have to handle some essential events

The most important part of programming is always that you need to know what events have happened. Knowing the environment of your program grants the possibility of reacting to the events. That's why you should always sign up the possible events of any tools you use.

Code 3 contains a single method call that signs your call object to all the events that need to be listened.

WireUpCallEvents();

Code 3 - It is easier to collect the event listeners in a new method

You could, of course, list the signing method calls in this method but you may want to use them at another time, so it is better to create a new private method for collecting them (Code 4).

The WireUpCallEvents() method signs up your call object to three separate events that are the change in the call state, receiving a DTMF signal and the essential event of error occurring.

private void WireUpCallEvents()
        {
            call.CallStateChanged += new EventHandler<VoIPEventArgs<CallState>>(call_CallStateChanged);
            call.DtmfReceived += new EventHandler<VoIPEventArgs<OzTuple<VoIPMediaType, DtmfSignal>>>(call_DtmfReceived);
            call.CallErrorOccured += new EventHandler<VoIPEventArgs<CallError>>(call_CallErrorOccured);
        }

Code 4 - You have to sign up your call object to all possible events

Now, your softphone is ready to make a voice call; there is only one step left, you have to start the call.

For making a voice call, just say Start

Using Ozeki VoIP SIP SDK means that you don't have to worry about the background actions when you want to build a softphone. The SDK provides you extraordinary support, so after you set some parameters as you did before, you will only need to make one single method call to make a voice call (Code 5).

call.Start();

Code 5 - Ozeki VoIP SIP SDK makes the hard work, you just have to ask for it

At this point your softphone Pick Up button has the functionality of initiating a phone call if the network settings are provided and the textBox on your softphone form contains a valid contact identifier.

You will also need to end your calls

At some point you will need to end a voice call properly. This funcionality usually attached to the Hang Up button so you will need to write an EventHandler method for this button's Click event.

Double clicking on the Pick Up button on the Design tab will direct you to the default EventHandler method generated by the Visual Studio. You can again rename the method, if you wish.

Ending a call is even simpler than starting one as you only have to call the HangUp() method provided by Ozeki VoIP SIP SDK and set the call object to null value (Code 6).

The method should contain an essential conditional checking of the call's existence and it needs to set the inComingCall logical field false. This informs the softphone about the end of the call.

if (call != null)
{
        if (inComingCall && call.CallState==CallState.Ringing)
            call.Reject();
        else
            call.HangUp();
        inComingCall = false;
        call = null;
}
textBox1.Text = string.Empty;

Code 6 - Ozeki VoIP SIP SDK provides the simplicity of ending a call with one method call

Now, your softphone can start and end voice calls. It is time to cover the .wav playing topic.

It is time to integrate the .wav playing support

There are some occasions when you will want to play an audio file with your softphone. These are usually the cases when you got an audio message or when you want to transfer the call and send some music to the contact so they can listen to it while waiting for the call transfer.

You can also use .wav playing in case of a customer service phone line. In this case the softphone will play some prerecorded audio information according to the buttons the caller pressed. You can navigate the caller through the customer service menu using these audio files and you can also solve some usual problem with prerecorded answers while at the meantime your help desk agents can solve more difficult customer problems.

Ozeki VoIP SIP SDK grants an excellent support for .wav audio file playing, so you will only have to call some prewritten methods in this case too. But first, your softphone GUI needs some improvement to provide space for the .wav playing.

Make some improvement on your GUI for .wav support

The softphone GUI you used till this time was capable of fulfill all the main functions of a simple softphone. Now, it is time to make some improvements on the GUI.

First you will need some extra space to be able to put the new functional elements down so you should resize the main form of the softphone. You can do this with your mouse by clicking on the form and dragging the little squares on the sides or in the corners. The other way is to modify the Size property of the form on the Properties panel.

You will need some space for a textbox and some new function buttons that you can put on the right side of the softphone. For achieving this, resize your softphone main form like you can see in Figure 4.


Figure 4 - You need to resize the main form to get space for the .wav support

You could only drop down some buttons and a textbox on the form, but it is a more sophisticated method to use a GroupBox object that will ensure that you will see what GUI elements are related to the same functionality (Figure 5).


Figure 5 - The GroupBox GUI element helps you to group the functionalities on the form

Now, you will need some other GUI elements to be able to open, play and stop a .wav audio file. You should use a TextBox and three buttons for these purposes. The TextBox will contain the file name and location, and the buttons will function as browse/open, play and stop.
After adding these elements to your GUI, it will look similar to the one in Figure 6.


Figure 6 - After adding some elements, your GUI is ready for .wav playing

You have an impressive and fully improved GUI, now, it is time to write some functionality to make the new elements work. You will mainly have to write the default EventHandler methods for all three buttons and some helping methods supported by the Ozeki VoIP SIP SDK.

Use the extraordinary support of Ozeki VoIP SIP SDK tools

Ozeki VoIP SIP SDK provides you a very useful tool called WaveStreamPlayback. It is an object type that will grant you all the background activities for playing .wav files. You only have to call the granted methods.

The WaveStreamPlayback class is a MediaHandler that provides you the methods for starting, stopping and pausing the .wav playing. It has a field for checking if the audio is being played and it provides you an Event when the audio playing has stopped.

Your job is just to call these methods and check the state of the player to be able to make your softphone work properly with .wav file playing.

Which audio file do you want to play?

For playing an audio file, you will need an audio file. Note that Ozeki VoIP SIP SDK supports uncompressed .wav audio files, so you will need to use this type of audio files.

Code 7 shows the EventHandler method for the Open button. The buttons on the form has been renamed for buttonOpenPlayback, buttonStartPlayback and buttonStopPlayback. The textbox got the name of textBoxPlaybackFile.

When you press the Open button you need a dialog to open on that you can browse for the .wav file to open. Windows Forms grant you an easy to use method for these pop-up windows. You only have to ask for an OpenFileDialog and the exact opening window will appear.

You can parameterize the open window to be able to open only one or more files at the same time and you can specify the file filter to use. The file filter defines the extension of the files you want to open.

Code 7 shows how to initialize an open dialog that can open only one file at a time and that opens audio files with .wav extension. Opening a file will be shown on the main form by modifying the Text property of the textBoxPlaybackFile textbox.

...
using (OpenFileDialog ofd = new OpenFileDialog() { Multiselect = false, Filter = "Wave Files (*.wav)|*.wav" })
            {
                if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                    textBoxPlaybackFile.Text = ofd.FileName;
            }
...

Code 7 - You will need an OpenFileDialog for choosing a .wav file

File opening is only the first step towards audio playing, especially because this method only specifies the audio file to be played. You will now need to write the playing method with the support of the Ozeki VoIP SIP SDK and attach it to the Start button.

You will need to start the devices

For playing .wav files you will need to initialize the main devices you will use (Code 8). The audio file path was put in the Text property of the textBoxPlaybackFile GUI element so you can add that as a parameter for the WaveStreamPlayback constructor.

Your application should be informed when the audio playing stops, so you will need to sign your WaveStreamPlayback object to this event. This is shown in line 2 of Code 8.

The textbox Text can be modified during the audio playing so you will need to know if you are still playing the right file. This example program uses the simplest solution for this problem with a string variable that is set to the previously opened audio file path. You will need to check if the current text equals the previous one to play the right audio.

Now it is time to start the speaker and connect it to the WaveStreamPlayback object. These methods are fully written in the Ozeki VoIP SIP SDK, so you only have to call them with the right parameters.

WaveStreamPlayback = new WaveStreamPlayback(textBoxPlaybackFile.Text);
WaveStreamPlayback.Stopped += (WaveStreamPlayback_Stopped);
prevaudiofile = textBoxPlaybackFile.Text;
speaker.Start();
connector.Connect(WaveStreamPlayback, speaker);

Code 8 - You can start the necessary devices by calling Ozeki VoIP SIP SDK provided methods

You will have to write a simple EventHandler method for handling the audio playing stopped event. It is a really easy task show in Code 9 as Ozeki VoIP SIP SDK grants you the main concept for this purpose too.

void WaveStreamPlayback_Stopped(object sender, EventArgs e)
        {
            if (PlaybackStopped != null)
                PlaybackStopped(this, EventArgs.Empty);
        }

Code 9 - You always need to know about the possible events and handle them

Opening a WaveStreamPlayback object always holds the possibility of an opening error. You mistype the path of the .wav file and the WaveStreamPlayback initialization will fail at once. You will need to make some Exception handling for this purpose.

The catch block shown in Code 10 only pops up a message box when the filename or path is not correct. You can naturally write more proper solutions, but in case of this example program, this will do.

catch (Exception ex)
                    {
                        if (WaveStreamPlayback == null)
                        {
                            MessageBox.Show(String.Format("The file location of your .wav file is incorrect.\n {0}", ex.Message), string.Empty, MessageBoxButtons.OK,
                     MessageBoxIcon.Error);
                            return;
...

Code 10 - Exception handling prevents the crash of your application

After all the devices and tools are started, you will be able to start the audio playing. Playing an audio file is called streaming.

WaveStreamPlayback starts playing if you ask for it

Ozeki VoIP SIP SDK provides the solution for streaming an audio file, you will only have to call the StartStreaming() method and the audio playing will start.

As this example uses one button for starting and pausing the audio streaming, the Text property of the buttonStartPlayback object should be modified every time the button is pressed.

The IsStreaming property of the WaveStreamPlayback object provides the information that the audio file is being played or not. You can check this property to write some conditional instructions for setting the proper functionality.

if (!WaveStreamPlayback.IsStreaming)
                {
                    buttonStartPlayback.Text = "Pause";
                    WaveStreamPlayback.StartStreaming();
                    WaveStreamPlayback.IsStreaming = true;
                }

Code 11 - Starting the audio playing is only a method call

After you started audio playing, you have to consider pausing and stopping the stream too. As for the Pause functionality, you can use the same button as in case of starting.

You can use the same button for two functionalities

Code 12 shows an example of coding the pause function in your application. Ozeki VoIP SIP SDK class WaveStreamPlayback also provides you the pausing function, so you only have to call the PauseStreaming() method for this purpose.

When a stream is paused, you will need to modify the Text property of the buttonStartPlayback button to indicate that the button has the starting function again. You will also need to set the IsStreaming property to false so the program will use the start functionality again.

buttonStartPlayback.Text = "Start";
WaveStreamPlayback.PauseStreaming();
WaveStreamPlayback.IsStreaming = false;

Code 12 - Start and Pause functions are usually attached to the same button

Now, your Start/Pause button has all the functions to perform, it is time to write some functionality for the Stop button too.

You will also need to stop playing

If an audio stream started, it will definitely stop when the stream reaches the end of the file, but you will need to end the streaming process before that time too.

The difference between pausing and stopping an audio stream is that in case of pausing the audio stream will continue playing from the point you paused it when starting the stream. In case of stopping, the playing will start from the beginning of the file.

Code 13 shows an example for stopping the audio stream properly. Naturally, the method will do nothing when there is no stream playing. For this you should check the existence of the WaveStreamPlayback object.

When you stop playing an audio file, you will need to call the Ozeki VoIP SIP SDK provided StopStreaming() method and you will also have to stop the used devices and disconnect the WaveStreamPlayback object from the speaker.

One of the most important steps of stopping an audio stream is to call the Dispose() method that will free the lock on the audio file. This is important when you want to use that audio file for other purposes (like recording).

if (WaveStreamPlayback != null)
            {
                WaveStreamPlayback.StopStreaming();
                buttonStartPlayback.Text = "Start";
                speaker.Stop();
                connector.Disconnect(WaveStreamPlayback, speaker);
                WaveStreamPlayback.Dispose();
                WaveStreamPlayback = null;
            }

Code 13 - You always need to be able to stop anything you have started

Now your softphone application is fully capable of opening, playing, pausing and stopping a .wav audio file. If you followed the guide properly you are familiar with all the necessary tools and you can improve your application even further using the Ozeki VoIP SIP SDK.

Further development possibilities

This sample program is only for handling one telephone line. However, Ozeki VoIP SIP SDK offers the opportunity to develop and handle multiple telephone lines simultaneously. Moreover further functions can also be implemented effectively like call forwarding and chat function.

This article contained a complete guide for programming voice calling and the support of .wav audio file playing using the Ozeki VoIP SIP SDK provided tools and methods. If you have followed the article, you are now capable of using the excellent support of Ozeki VoIP SIP SDK for voice call and audio playing solutions. Now it is time for stepping forward and making your own application with these functions.

If you have any questions or need assistance, contact us at info@voip-sip-sdk.com

You can select an Ozeki VoIP SIP SDK license for your project on How to buy page

You can download a simple .wav example audio file to check if your program works properly.
Download a sample .wav audio file to test your program now

Related Pages

Operating system: Windows 8, Windows 7, Vista, 200x, XP
Development environment: Visual Studio 2010 (Recommended), Visual Studio 2008, Visual Studio 2005
Programming language: C#.NET
Supported .NET framework: .NET Framework 4.5, .NET Framework 4.0, .NET Framework 3.5 SP1
Software development kit: OZEKI VoIP SIP SDK (Download)
VoIP connection: 1 SIP account
System memory: 512 MB+
Free disk space: 100 MB+