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

A full-duplex audio player in C# using the waveIn/waveOut APIs

Rate me:
Please Sign up or sign in to vote.
4.75/5 (113 votes)
31 Aug 20033 min read 2.1M   22.3K   262   362
An article on low-level audio capture and playback using the waveIn/waveOut APIs through P/Invoke in C#.

Sample Image - cswavrec.gif

Introduction

As I already mentioned in my article A low-level audio player in C#, there are no built-in classes in the .NET framework for dealing with sound. This holds true not only for audio playback, but also for audio capture.

It should be noted, though, that the Managed DirectX 9 SDK does include classes for high-level and low-level audio manipulation. However, sometimes you don’t want your application to depend on the full DX 9 runtime, just to do basic sound playback and capture, and there are also some areas where Managed DirectSound doesn’t help at all (for example, multi-channel sound playback and capture).

Nevertheless, I strongly recommend you to use Managed DirectSound for sound playback and capture unless you have a good reason for not doing so.

This article describes a sample application that uses the waveIn and waveOut APIs in C# through P/Invoke to capture an audio signal from the sound card’s input, and play it back (almost) at the same time.

Using the code

The sample code reuses the WaveOutPlayer class from my article A low-level audio player in C#. The new classes in this sample are WaveInRecorder and FifoStream.

The FifoStream class extends System.IO.Stream to implement a FIFO (first-in first-out) of bytes. The overridden Write method adds data to the FIFO’s tail, and the Read method peeks and removes data from the FIFO’s head. The Length property returns the amount of buffered data at any time. Calling Flush will clear all pending data.

The WaveInRecorder class is analogous to the WaveOutPlayer class. In fact, if you look at the source files, you’ll notice that the implementations of these classes are very similar. As with WaveOutPlayer, the interface of this class has been reduced to the strict minimum.

Creating an instance of WaveInRecorder will cause the system to start recording immediately. Here’s the code that creates the WaveOutPlayer and WaveInRecorder instances.

C#
private void Start()
{
    Stop();
    try
    {
        WaveLib.WaveFormat fmt = new WaveLib.WaveFormat(44100, 16, 2);
        m_Player = new WaveLib.WaveOutPlayer(-1, fmt, 16384, 3, 
                        new WaveLib.BufferFillEventHandler(Filler));
        m_Recorder = new WaveLib.WaveInRecorder(-1, fmt, 16384, 3, 
                        new WaveLib.BufferDoneEventHandler(DataArrived));
    }
    catch
    {
        Stop();
        throw;
    }
}

The WaveInRecorder constructor takes five parameters. Except for the last parameter, their meaning is the same as in WaveOutPlayer.

The first parameter is the ID of the wave input device that you want to use. The value -1 represents the default system device, but if your system has more than one sound card, then you can pass any number from 0 to the number of installed sound cards minus one, to select a particular device.

The second parameter is the format of the audio samples.

The third and forth parameters are the size of the internal wave buffers and the number of buffers to allocate. You should set these to reasonable values. Smaller buffers will give you less latency, but the captured audio may have gaps on it if your computer is not fast enough.

The fifth and last parameter is a delegate that will be called periodically as internal audio buffers are full of captured data. In the sample application we just write the captured data to the FIFO, like this:

C#
private void DataArrived(IntPtr data, int size)
{
    if (m_RecBuffer == null || m_RecBuffer.Length < size)
        m_RecBuffer = new byte[size];
    System.Runtime.InteropServices.Marshal.Copy(data, m_RecBuffer, 0, size);
    m_Fifo.Write(m_RecBuffer, 0, m_RecBuffer.Length);
}

Similarly, the Filler method is called every time the player needs more data. Our implementation just reads the data from the FIFO, as shown below:

C#
private void Filler(IntPtr data, int size)
{
    if (m_PlayBuffer == null || m_PlayBuffer.Length < size)
        m_PlayBuffer = new byte[size];
    if (m_Fifo.Length >= size)
        m_Fifo.Read(m_PlayBuffer, 0, size);
    else
        for (int i = 0; i < m_PlayBuffer.Length; i++)
            m_PlayBuffer[i] = 0;
    System.Runtime.InteropServices.Marshal.Copy(m_PlayBuffer, 
                                                 0, data, size);
}

Note that we declared the temporary buffers m_RecBuffer and m_PlayBuffer as member fields in order to improve performance by saving some garbage collections.

To stop streaming, just call Dispose on the player and capture objects. We also need to flush the FIFO so that the next time Start is called there is no residual data to play.

C#
private void Stop()
{
    if (m_Player != null)
        try
        {
            m_Player.Dispose();
        }
        finally
        {
            m_Player = null;
        }
    if (m_Recorder != null)
        try
        {
            m_Recorder.Dispose();
        }
        finally
        {
            m_Recorder = null;
        }
    m_Fifo.Flush(); // clear all pending data
}

Conclusion

This sample demonstrates how to combine the waveIn and waveOut APIs in C#. As an exercise, you may want to combine this code with the audio effect framework in the article Programming Audio Effects in C#, to apply effects to a live audio input in real-time, although latency may be an issue for certain applications.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
Luxembourg Luxembourg
Ianier Munoz lives in France and works as a senior consultant and analyst for an international consulting firm. His specialty is in multimedia applications, and he has authored some popular software, such as American DJ's Pro-Mix, Chronotron and Adapt-X.

Comments and Discussions

 
GeneralRe: How can i implement it over network? Pin
mira_cris17-Jul-06 2:47
mira_cris17-Jul-06 2:47 
GeneralAnother Question Pin
wxhsplash27-Jan-06 20:24
wxhsplash27-Jan-06 20:24 
QuestionHow can I play a wav file just one time? Pin
wxhsplash26-Jan-06 20:10
wxhsplash26-Jan-06 20:10 
AnswerRe: How can I play a wav file just one time? Pin
Ianier Munoz27-Jan-06 6:30
Ianier Munoz27-Jan-06 6:30 
General.Net 2.0 Problems Pin
Nekro16-Dec-05 21:37
Nekro16-Dec-05 21:37 
GeneralRe: .Net 2.0 Problems Pin
Ianier Munoz16-Dec-05 21:40
Ianier Munoz16-Dec-05 21:40 
GeneralRe: .Net 2.0 Problems Pin
Nekro16-Dec-05 23:06
Nekro16-Dec-05 23:06 
GeneralRe: .Net 2.0 Problems Pin
Ianier Munoz16-Dec-05 23:13
Ianier Munoz16-Dec-05 23:13 
GeneralRe: .Net 2.0 Problems Pin
Nekro16-Dec-05 23:33
Nekro16-Dec-05 23:33 
GeneralRe: .Net 2.0 Problems Pin
Ianier Munoz17-Dec-05 0:00
Ianier Munoz17-Dec-05 0:00 
GeneralRe: .Net 2.0 Problems Pin
SuperMomo_net7-Dec-09 1:53
SuperMomo_net7-Dec-09 1:53 
GeneralRe: .Net 2.0 Problems Pin
Adam Cheong24-Feb-10 3:51
Adam Cheong24-Feb-10 3:51 
GeneralCreating a live VU meter Pin
woodced12-Dec-05 6:54
woodced12-Dec-05 6:54 
GeneralWaveform audio interface component for .NET Pin
AdamSlosarski4-Nov-05 0:34
AdamSlosarski4-Nov-05 0:34 
GeneralThis example in Windows 98 Pin
srenzi20-Oct-05 4:58
srenzi20-Oct-05 4:58 
GeneralSHOUTcast stream Pin
jmarcos18-Oct-05 16:15
jmarcos18-Oct-05 16:15 
GeneralFull Duplex Audio Pin
Member 14597834-Sep-05 20:15
Member 14597834-Sep-05 20:15 
GeneralCompact Framework Pin
gfi8225-Aug-05 4:02
gfi8225-Aug-05 4:02 
Generalnetmeeting session Pin
mitiakov25-Aug-05 3:26
mitiakov25-Aug-05 3:26 
Generalsaving to file Pin
Anonymous12-Jul-05 7:42
Anonymous12-Jul-05 7:42 
GeneralRe: saving to file Pin
Ianier Munoz18-Aug-05 8:28
Ianier Munoz18-Aug-05 8:28 
GeneralSaving filler output to array to play back later. Pin
tom_coombs29-Jun-05 0:29
tom_coombs29-Jun-05 0:29 
GeneralTransfer sound over network Pin
Member 13746506-Jun-05 20:21
Member 13746506-Jun-05 20:21 
GeneralRe: Transfer sound over network Pin
Ianier Munoz18-Jun-05 21:34
Ianier Munoz18-Jun-05 21:34 
GeneralDelay Pin
skcrpk24-Apr-05 6:04
skcrpk24-Apr-05 6:04 

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.