Playing a CD with the Win32 Media Control Interface

A long time ago I wrote some code to play CD audio tracks for a game engine I was writing. CD audio (via mixed mode CDs) was popular for video game music at the time because it allowed for high quality music without having to deal with large un-compressed audio files (e.g. uncompressed WAV) or relatively expensive decompression algorithms with compressed files (e.g. MP3).

I cleaned up the code a bit and decided to post it here. It’s surprising simple code as it uses the very high-level Media Control Interface (MCI).

Compiling and Linking

You must link with winmm.lib

cdaudio.h

#ifndef __CDAUDIO__H__
#define __CDAUDIO__H__

bool cdaudio_open(void);
void cdaudio_play(int track);
void cdaudio_stop(void);
void cdaudio_close(void);

#endif

cdaudio.cpp

#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif

#include
<windows.h>
#include <stdio.h>
#include <stdarg.h>
#include <mmsystem.h>

bool cdaudio_open(void)
{
    DWORD ret = mciSendString(L
"open cdaudio",NULL,NULL,NULL);
    mciSendString(L
"set cdaudio time format tmsf",NULL,NULL,NULL);

    
if (ret != 0) {
        
return false;
    }

    
return true;
}

void cdaudio_play(int track)
{
    
wchar_t tk_string[32];
    wsprintf(tk_string, L
"play cdaudio from %i to %i", track, track+1);
    mciSendString(tk_string,NULL,NULL,NULL);
}


void cdaudio_stop(void)
{
    mciSendString(L
"stop cdaudio",NULL,NULL,NULL);

}

void cdaudio_close(void)
{
    mciSendString(L
"stop cdaudio",NULL,NULL,NULL);
    mciSendString(L
"close cdaudio",NULL,NULL,NULL);
}

main.cpp (example showing how to use cdaudio functions to play track)

#include <stdio.h>
#include "cdaudio.h"

int main(int argc, char *argv[])
{
    
// setup MCI for CD audio
    
cdaudio_open();

    
// play track 8 on CD
    
cdaudio_play(8);

    wprintf(L
"Press any key to stop playing track...");
    getchar();
// wait for keypress

    // cleanup
    
cdaudio_close();


    
return 0;
}