Larry Osterman's WebLog

Confessions of an Old Fogey
Blog - Title

Playing Audio CDs, part 2

Playing Audio CDs, part 2

  • Comments 7
Yesterday, I looked a a simple application for dumping the track information on a CD.

Since I'm going to be working on this concept (playing a CD) for a while, I figured I'd restructure the app to make it somewhat more generic.

First off, lets define a pure virtual base class for the player...

class CCDPlayer
{
public:
    virtual ~CCDPlayer(void) {};
    virtual HRESULT Initialize() = 0;
    virtual HRESULT DumpTrackList() = 0;
    virtual HRESULT PlayTrack(int TrackNumber) = 0;
};
 

It's a really trivial class, it defines an Initialization step, dumping the tracks and playing a track. 

Now, lets take the core application and rewrite it using this base class.


int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
    int nRetCode = 0;
    CWMPCDPlayer wmpCdPlayer;
    CCDPlayer *player = &wmpCdPlayer;
    HRESULT hr;

    // initialize MFC and print and error on failure
    if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
    {
        // TODO: change error code to suit your needs
        _tprintf(_T("Fatal Error: MFC initialization failed\n"));
        nRetCode = 1;
    }
    else
    {
        hr = player->Initialize();
        if (hr != S_OK)
        {
            printf("Couldn't initialize CD player: %x\n", hr);
            return 1;
        }
        hr = player->DumpTrackList();
        if (hr != S_OK)
        {
            printf("Couldn't dump track database: %x\n", hr);
            return 1;
        }
        int trackNumber;
        printf("Pick a track: ");
        scanf("%d", &trackNumber);
        hr = player->PlayTrack(trackNumber);
    }

    return nRetCode;
}

Much better (simpler).  Now we can concentrate on the meat of the problem, the actual player implementation.

Here's a complete implementation of the CWMPCDPlayer class:

CWMPCDPlayer::CWMPCDPlayer(void)
{
}
CWMPCDPlayer::~CWMPCDPlayer(void)
{
    CoUninitialize();
}
HRESULT CWMPCDPlayer::Initialize()
{
    HRESULT hr;
    hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
    if (hr != S_OK)
    {
        printf("Couldn't initialize COM: %x\n", hr);
        return hr;
    }
    hr = _CdRomCollection.CoCreateInstance(__uuidof(WMPLib::WindowsMediaPlayer));
    if (hr != S_OK)
    {
        printf("Couldn't instantiate CDRom player: %x\n", hr);
        return hr;
    }

    long driveCount;
    hr = _CdRomCollection->get_count(&driveCount);
    if (hr != S_OK)
    {
        printf("Couldn't get drive count: %x\n", hr);
        return hr;
    }
    if (driveCount == 0)
    {
        printf("Machine has no CDROM drives\n");
        return E_FAIL;
    }
    return S_OK;
}
HRESULT CWMPCDPlayer::DumpTrackList()
{
    HRESULT hr;
    CComPtr<WMPLib::IWMPCdrom> cdromDrive;
    cdromDrive = _CdRomCollection->Item(0);

    hr = cdromDrive->get_Playlist(&_Playlist);
    if (hr != S_OK)
    {   
        printf("Couldn't get playlist for CDRom drive: %x\n", hr);
        return hr;
    }
    for (int i = 0 ; i < _Playlist->count ; i += 1)
    {
        CComPtr<WMPLib::IWMPMedia> item;
        hr = _Playlist->get_Item(i, &item);
        if (hr != S_OK)
        {
            printf("Couldn't get playlist item %d: %x\n", i, hr);
            return hr;
        }
        printf(_T("Track %d (%S)\n"), i, item->name.GetBSTR());
    }
    return S_OK;
}

HRESULT CWMPCDPlayer::PlayTrack(int TrackNumber)
{
    HRESULT hr;
    CComPtr<WMPLib::IWMPPlayer> player;
    CComPtr<WMPLib::IWMPControls> controls;
    CComPtr<WMPLib::IWMPMedia> media;
    hr = player.CoCreateInstance(__uuidof(WMPLib::WindowsMediaPlayer));
    if (hr != S_OK)
    {
        printf(_T("Couldn't create player instance: %x\n"), hr);
        return hr;
    }
    hr = player->put_currentPlaylist(_Playlist);
    if (hr != S_OK)
    {
        printf(_T("Couldn't set player playlist: %x\n"), hr);
        return hr;
    }
    hr = player->get_controls(&controls);
    if (hr != S_OK)
    {
        printf(_T("Couldn't get player controls: %x\n"), hr);
        return hr;
    }

    hr = _Playlist ->get_Item(TrackNumber, &media);
    if (hr != S_OK)
    {
        printf(_T("Couldn't get playlist item: %x\n"), hr);
        return hr;
    }

    hr = controls->put_currentItem(media);
    if (hr != S_OK)
    {
        printf(_T("Couldn't set player control item: %x\n"), hr);
        return hr;
    }
    hr = controls->play();
    if (hr != S_OK)
    {
        printf(_T("Couldn't get playlist item: %x\n"), hr);
        return hr;
    }
    double duration;
    hr = media->get_duration(&duration);
    if (hr != S_OK)
    {
        printf(_T("Couldn't get track duration: %x\n"), hr);
        return hr;
    }
    //
    // Wait for the track to stop playing.
    //
    MSG msg;
    DWORD tickCountStart = ::GetTickCount();
    while (GetMessage(&msg, NULL, 0, 0) && GetTickCount() < tickCountStart+(duration*1000))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
    return S_OK;
}

That's it! I left out the WMP Cdplayer class definition, it consists of a derivation of the base class, and the addition of two member variables:

    CComPtr<WMPLib::IWMPCdromCollection> _CdRomCollection;
    CComPtr<WMPLib::IWMPPlaylist> _Playlist;

These exist to carry information across the various abstract methods.

Most of the code above is a repackaging of the code from yesterdays example, the new bits are the PlayTrack method.  There looks like a lot of code in the playback code, but it's actually pretty straightforward.  You allocate a player object to actually perform the playback, and set the current playlist on the player.  You get access to the controls of the player (that's the controls object), tell the control what track to play, and then ask the control to start playing.

I then wait until the track completes before returning to the caller.  Please note that the wait loop pumps windows messages.  This is because we're an STA application and when you're in an STA application, you need to pump messages instead of blocking, because STA COM objects use windows messages to communicate (and the WMP class is an STA object).

Tomorrow, I'll talk about the next method for doing CD playback, the MCI command set.

  • What happens when I'm listening to a track during the afternoon of my 50th day of uptime and the tick count rolls over?
  • Drew,
    Then my stupid little application crashes and burns.

    I did say it wasn't production code, didn't I?
  • Sorry. I sometimes forget that I'm not looking for bugs in every piece of code I see.

    TODO: Curb my overactive tester Spidey-sense.
  • Drew, keep it up, it keeps me on my toes :)
  • So how can i make this little app pull up the track names if the CD has never been played before on WMP10?

    I noticed that the tracks show up as

    Track 1 (Track 1)
    Track 2 (Track 2)
    ...

    if the CD has never been played before in media player. But if I run the app after openign it once in media player, I get the track names just fine...

    BTW, I don't know the mechanism behind what kind of web service provides Audio CD's with track names and more metadata - It would be nice if you can talk a bit about this in your blog.
  • This is what I did for the timing loop:

    System.Threading.AutoResetEvent evt = new System.Threading.AutoResetEvent(false);
    evt.WaitOne((int)(duration * 1000), false);

    he he :)
  • Vatsan, I don't know, I don't have any CDs that fall into that category. Let me check a second...


    From the documentation for the media library:
    If the user plays a digital media file that is not added to Media Library, you have access to the attributes that are in the file.

    If the user plays a digital media file that has been added to Media Library, you have access to the attributes that are stored only in Media Library, the attributes that are stored only in the file, and the attributes that are stored in both Media Library and the file.

    Somehow you have to add the CD to the library, but I'm not sure how to do that... Sorry :(
Page 1 of 1 (7 items)