Click here to Skip to main content
Click here to Skip to main content
Go to top

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

, 31 Aug 2003
Rate this:
Please Sign up or sign in to vote.
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.

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:

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:

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.

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

Share

About the Author

Ianier Munoz
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

 
QuestionPlz help : How to record audio buffer to a .wav file PinmemberMember 865071615-Jan-14 1:59 
BugFound a bug in WaveStream.cs, the class WaveStream PinmvpSergey Alexandrovich Kryukov18-Dec-13 15:27 
Questionnullreferenceexception PinmemberMember 877069515-Jun-13 9:32 
AnswerHow to fix WaveOut for Windows 64-bit (fix Null Reference exception) PinmemberKevin North20-May-13 8:21 
GeneralRe: How to fix WaveOut for Windows 64-bit (fix Null Reference exception) PinmemberBillWoodruff25-Jun-13 6:42 
QuestionHi Mr. Ianier Munoz Pinmemberahmed5_273-Feb-13 9:33 
QuestionHow to save in a .Wav file ? Pinmembersmartradio3-Nov-12 8:20 
QuestionException is thrown while you start recording on Win7 Pinmemberprajaaaa22-Oct-12 21:20 
AnswerRe: Exception is thrown while you start recording on Win7 PinmemberWes Jones1-Mar-13 11:58 
QuestionWhere the file is saved on your computer Pinmembernomigan7-Jul-12 12:22 
GeneralMy vote of 5 PinmemberFarhan Ghumra6-Jun-12 21:38 
BugHangs on Stop Pinmembershivbuyya10-Mar-12 21:09 
AnswerRe: Hangs on Stop PinmemberAyrA.ch10-Apr-12 10:48 
GeneralRe: Hangs on Stop Pinmembershivbuyya4-Oct-12 23:12 
GeneralRe: Hangs on Stop PinmemberAyrA.ch23-Oct-12 7:24 
AnswerRe: Hangs on Stop Pinmembervozmen26-Jan-13 4:02 
GeneralRe: Hangs on Stop Pinmemberbimbambumbum27-Mar-13 9:35 
AnswerRe: Hangs on Stop Pinmembervozmen27-Mar-13 10:53 
GeneralRe: Hangs on Stop Pinmemberbimbambumbum27-Mar-13 23:29 
GeneralRe: Hangs on Stop PinmemberAriadne15-May-14 5:25 
GeneralMy vote of 5 PinmemberMember 10944438-Jan-12 18:56 
Questionhow can I get the sound data? PinmemberMember 79558498-Aug-11 2:48 
AnswerRe: how can I get the sound data? PinmemberMember 40308897-Jan-12 22:24 
GeneralListen voice in a particular sound card Pinmembersawass24-May-11 5:17 
Generalhow to save the recorded file? Pinmemberahloon18-Apr-11 4:26 
GeneralRe: how to save the recorded file? PinmemberChristian_N21-Jun-12 11:45 
GeneralPause recording Pinmemberotto40008-Feb-11 23:39 
GeneralBytes in file stream have only values 0, 1 and 255 [modified] PinmemberPedjabla30-Jan-11 7:07 
GeneralMy vote of 3 Pinmembernil14018-Dec-10 18:05 
Answercswavrec_src_AnyCpu Pinmemberisme_enjoy1-Dec-10 21:08 
GeneralUrgent Help Skype Call Recording Using C# Pinmembersyed_developer25-Oct-10 21:45 
GeneralMy vote of 5 PinmemberPsyris_25-Oct-10 5:36 
GeneralCompact Framework Pinmemberershad121-Oct-10 0:31 
GeneralDoes not work in x64 Pinmemberyasaralper29-Aug-10 2:15 
GeneralRe: Does not work in x64 PinmemberNAMEJ12-Mar-11 0:30 
GeneralRe: Does not work in x64 Pinmemberyasaralper13-Mar-11 10:36 
GeneralRe: Does not work in x64 PinmemberRoey C19-Jan-12 7:57 
GeneralRe: Does not work in x64 - example is in error Pinmemberjcameron2330-Nov-12 13:45 
Generaltwo USB-soundcards cause problems PinmemberMember 402255423-Aug-10 20:40 
QuestionI need digitized data [modified] Pinmemberrrsharif16-Aug-10 22:54 
GeneralC# saving Wav PinmemberFahed Al Daye1-Jun-10 6:56 
I am making an editor for the engine that will run both for Windows and xBox 360, I am using the XNA technology for the engine as it is the best for this stuff. However, the editor does not require the use of the XNA technology. How do I load sound in the form, have a button that plays the sound, stop the sound and then save the sound in my own .bin file?
 
Let us say the sound.bin have two sound files stored in them, not just a little c:\location\sound.wav string that directs it to the sound, but the actual two sounds are stored in the file. How do you do that? And Using the reverse method of saving these sounds to load them and store them in the array, array[0]=holds sound 1, array[1]=holds sound 2, then using the function I would be able to play that sound, how do I do that?
 
1) Click on the Add Sound button, a windows dialog box comes up. I select the .wav file I want to add.
2) When I select the file it stores it in an array and puts in the listbox: sound 0
3) I click Add Sound button again, a window dialog box comes up. I select the .wav file I want to add.
4) When I select the file it stores it in an array and puts in the listbox: sound 1
5) When I select the item in the listbox.selectIndex = 0, and press the Play button it plays the sound 0 from the Array[0] index.
6) When I select the item in the listbox.selectindex =1, and press the Play button it plays the sound 1 from the Array[1] index.
7) When I press the OK button in the Window, before the Window performs the action this.Close();, it saves the information in the Array in a file called test.bin.
8) The information that is stored in the Array is the actual sound, which is sound 0 and sound 1.
9) When the form loads, it executes the LoadSound() function I make and what it does it looks at the test.bin file and fills the Array[0] and Array[1] with Sound 0 and Sound 1
 
So what happens is that I toke an actual normal file0.wav and file1.wav and saved them both as a single file called test.bin. The test.bin holds sound0 and sound 1 or whatever sound name you called it with the actual file0.wav and file1.wav. When you open test.bin you see gibberish because it is two .wav files saved together as test.bin. The test.bin can hold as many .wav files you want. So let us say the first file0.wav is 12 KB and the second file1.wav is 12 KB, the test.bin should be 24 KB plus whatever bytes or KBs extra about the information of the sound. Can anyone help to the right direction how to achieve this? Thanks in advance.
Questionis it possible to duplicate channels ? Pinmembersr_dusad13-May-10 19:43 
Questionquestion Pinmemberfribe20-Apr-10 5:23 
Generaldelay Pinmemberjachuuu22-Mar-10 3:18 
GeneralRe: delay Pinmemberk6343002745-Apr-11 16:18 
Generalvs 2010... Pinmembergrummbunger12-Mar-10 13:29 
Generalecho Pinmemberxiscoverso9-Jan-10 1:05 
GeneralRe: echo Pinmemberalex let12-Feb-10 6:13 
GeneralDoesn't work if running on a 64 bit application. Pinmembercoder25519-Dec-09 9:25 
GeneralRe: Doesn't work if running on a 64 bit application. Pinmemberme200724-Feb-10 0:38 

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

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

| Advertise | Privacy | Mobile
Web02 | 2.8.140916.1 | Last Updated 1 Sep 2003
Article Copyright 2003 by Ianier Munoz
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid