Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / desktop / WTL

Playing Wave Resources

2.48/5 (11 votes)
22 Jun 2008CPOL2 min read 1   1.4K  
Playing Wave Resources using a low level audio API.

Introduction

If your application needs to play a Wave resource using a low level audio API, just follow the "Using the code" section below.

Using the code

It's simple: just include, instantiate, load, and play.

Add "RscWaveOut.h" and "RscWaveOut.cpp" to your project (for formats other than 22050Hz, 8bps, Mono, tweak some values in the CRscWaveOut class; that can be easily done). Go to Project settings > link > add "winmm.lib".

  1. Add a member
  2. C++
    CRscWaveOut m_RscWaveOut;
  3. Load a wave resource (in the OnInitDialog() or the constructor of the main class, for example)
  4. C++
    m_RscWaveOut.LoadWaveResource(IDR_WAVE_TICK_HIGH, AfxGetApp()->m_hInstance);
  5. Play the wave (under a button maybe)
  6. C++
    m_RscWaveOut.PlayWave();

Background

The situation was that my application had to include Wave files as a resource and play them quickly and frequently. There are other high-middle level audio APIs like the sndPlaySound function but I noticed that sndPlaySound internally creates and destroys a thread every time it plays a Wave. I guessed that was one reason for the noticeable sound latency in my application. I tried to use the low level audio API - waveOut~ and mmio~ functions. Fortunately I could encapsulate all the necessary functions in a class CRscWaveOut that you can apply to your project very quickly.

The CRscWaveOut class might be useful:

  • If a Wave file must be located in the resources of your project.
  • If the play must be quick and precise on time using a low level audio API.

Though I haven't tested this on Wave samples longer than 100ms, I guess the class will work successfully. If there is trouble, look close into the CallBack function of CRscWaveOut. By handling other messages than just the ones provided (e.g., MM_WOM_DONE), you can easily take care of buffering long Wave resources.

The sample is an MFC project but the core CRscWaveOut class is built on Win32 APIs so you can use that class in ATL, WTL, and Win32 projects. For example, I used some of the code for quick sound generation in my metronome ActiveX of www.groovedive.com.

History

  • 2008.06.23: Created.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)