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

A low-level audio player in C#

Rate me:
Please Sign up or sign in to vote.
4.87/5 (94 votes)
27 Aug 20033 min read 953.2K   16.5K   240   171
This article describes a sample application that uses the waveout API in C#.

Sample Image - cswavplay.gif

Introduction

It is no news that the .NET framework does not include any classes for dealing with sound. Some people have worked around this limitation by wrapping high-level system components, such as Windows Media Player or DirectShow, into .NET-friendly libraries. However, most of these libraries are designed in such a way that they cannot be used to manipulate audio samples on the fly because they do not give you access to the actual sound data.

When developing applications that deal with such low-level issues, the most commonly used technologies are DirectSound and the waveout API. This article describes a sample application that uses the waveout API in C# through Interop to play a WAV file in a continuous loop.

Using the code

Most of the work in the sample application is carried out by two classes: WaveStream and WaveOutPlayer.

The WaveStream class extends System.IO.Stream and implements the necessary code to read audio samples from a WAV file. The constructor reads the file header and extracts all the relevant information including the actual length of the stream and the format of the audio samples, which is exposed through the Format property.

One important thing to note is that seeking operations in the WaveStream class are relative to the sound data stream. This way you don't have to care about the length of the header or about those extra bytes at the end of the stream that don't belong to the audio data chunk. Seeking to 0 will cause the next read operation to start at the beginning of the audio data.

The WaveOutPlayer class is where the most interesting things happen. For the sake of simplicity, the interface of this class has been reduced to the strict minimum. There are no Start, Stop or Pause methods. Creating an instance of WaveOutPlayer will cause the system to start streaming immediately.

Let's have a look at the code that creates the WaveOutPlayer instance. As you can see, the constructor takes five parameters:

C#
private void Play()
{
    Stop();
    if (m_AudioStream != null)
    {
        m_AudioStream.Position = 0;
        m_Player = new WaveLib.WaveOutPlayer(-1, m_Format, 16384, 3, 
            new WaveLib.BufferFillEventHandler(Filler));
    }
}

The first parameter is the ID of the wave 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. In this example, the format is taken directly from the wave stream.

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 audio may stutter if your computer is not fast enough.

The fifth and last parameter is a delegate that will be called periodically as internal audio buffers finish playing, so that you can feed them with new sound data. In the sample application we just read audio data from the wave stream, like this:

C#
private void Filler(IntPtr data, int size)
{
    byte[] b = new byte[size];
    if (m_AudioStream != null)
    {
        int pos = 0;
        while (pos < size)
        {
            int toget = size - pos;
            int got = m_AudioStream.Read(b, pos, toget);
            if (got < toget)
                m_AudioStream.Position = 0; // loop if the file ends
            pos += got;
        }
    }
    else
    {
        for (int i = 0; i < b.Length; i++)
            b[i] = 0;
    }
    System.Runtime.InteropServices.Marshal.Copy(b, 0, data, size);
}

Please note that this delegate may be called from any internal thread created by the WaveOutPlayer object, so if you want to call into your Windows Forms objects you should use the Invoke mechanism.

To stop playing, just call Dispose on the player object, like this:

C#
private void Stop()
{
    if (m_Player != null)
    try
    {
        m_Player.Dispose();
    }
    finally
    {
        m_Player = null;
    }
}

Conclusion

This sample demonstrates how to use the waveout API from C#. This is useful for applications that require more control on the audio stream compared to what other higher level libraries offer. Typical examples are applications that generate or modify audio samples on the fly, such as digital effect processors.

A modified version of this sample that implements support for DirectX plug-ins is included in the Adapt-X SDK, which is a commercial product that can be found at www.chronotron.com.

History

Update 28 Aug 03 - Fixed a bug related to reading the WAV file header.

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

 
AnswerRe: little error Pin
zonksoft12-Mar-09 7:15
zonksoft12-Mar-09 7:15 
GeneralCan't download Pin
Jörgen Ellberg8-Sep-08 21:54
Jörgen Ellberg8-Sep-08 21:54 
Questionprogress bar help Pin
TowerTurtle18-Aug-08 13:28
TowerTurtle18-Aug-08 13:28 
GeneralWMA player Pin
monchi868713-Aug-08 8:05
monchi868713-Aug-08 8:05 
GeneralListener Pin
bethany23-Jul-08 21:22
bethany23-Jul-08 21:22 
GeneralPlaying once Pin
moserwi9-Jun-08 2:52
moserwi9-Jun-08 2:52 
GeneralRe: Playing once Pin
xavier.fischer4-Jul-08 6:27
xavier.fischer4-Jul-08 6:27 
GeneralRe: Playing once (little fix) Pin
Claudio Nicora3-Jun-09 2:03
Claudio Nicora3-Jun-09 2:03 
I used your patched version to play a file un-looped and I noticed a little bug.
If you play a file shorter than the buffer size, it plays twice (then stops).

You're missing a break in Filler function:

private void Filler(IntPtr data, int size, ref bool finished)
{
    byte[] b = new byte[size];
    if (m_AudioStream != null)
    {
        int pos = 0;
        while (pos < size)
        {
            int toget = size - pos;
            int got = m_AudioStream.Read(b, pos, toget);
            if (got < toget)
            {
                finished = true; // notify end of playing
                m_AudioStream.Position = 0; // loop if the file ends
                break;
            }
            pos += got;
        }
    }
    else
    {
        for (int i = 0; i < b.Length; i++)
            b[i] = 0;
    }
    System.Runtime.InteropServices.Marshal.Copy(b, 0, data, size);
}

Thanks for your patch Smile | :)


Visit my website for some interesting .NET free tools: http://coolsoft.altervista.org

Generalend of recording Pin
bethany22-Apr-08 0:03
bethany22-Apr-08 0:03 
GeneralProgram Errors on play Pin
Derek Bartram19-Apr-08 7:39
Derek Bartram19-Apr-08 7:39 
GeneralPCM Audio is not compressed using WriteSample Pin
Member 406820714-Apr-08 19:03
Member 406820714-Apr-08 19:03 
QuestionJust use SoundPlayer? Pin
Paul Shaffer9-Apr-08 11:23
Paul Shaffer9-Apr-08 11:23 
AnswerRe: Just use SoundPlayer? Pin
moserwi9-Jun-08 0:52
moserwi9-Jun-08 0:52 
GeneralRe: Just use SoundPlayer? Pin
K Haynie7-Jan-10 5:58
K Haynie7-Jan-10 5:58 
AnswerRe: Just use SoundPlayer? Pin
Clutchplate20-Nov-08 14:38
Clutchplate20-Nov-08 14:38 
GeneralThanks! Pin
geekisi7721-Oct-07 12:52
geekisi7721-Oct-07 12:52 
QuestionHow to pause while recording Pin
rajvijay18-Oct-07 23:12
rajvijay18-Oct-07 23:12 
Questionquestion about wav using Pin
headburster21-Aug-07 23:33
headburster21-Aug-07 23:33 
GeneralArgumentException -> Windows Mobile 5.0 Pin
user1403787-May-07 3:51
user1403787-May-07 3:51 
GeneralRe: ArgumentException -> Windows Mobile 5.0 Pin
eelioss20-May-07 8:21
eelioss20-May-07 8:21 
GeneralRe: ArgumentException -> Windows Mobile 5.0 Pin
wimpos3-Sep-07 1:47
wimpos3-Sep-07 1:47 
GeneralMagic number Pin
Giles Bathgate28-Apr-07 2:30
Giles Bathgate28-Apr-07 2:30 
GeneralRe: Magic number Pin
Ianier Munoz30-Apr-07 19:01
Ianier Munoz30-Apr-07 19:01 
GeneralRe: Magic number Pin
k06a8-Apr-10 10:36
k06a8-Apr-10 10:36 
Generalnoise filterring system Pin
hassan053116-Mar-07 23:29
hassan053116-Mar-07 23:29 

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.