Eric Niebler
Eric Niebler

Reputation: 6177

Cannot play mp3 with mciSendString in C++ console application

I'm trying to play an mp3 file from a win32 C++ console application. From what I've read online, mciSendString is the API I'm looking for, and I expected the following to work but it doesn't.

#include <cstdio>
#include <array>

#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <mmsystem.h>
using namespace std;

#pragma comment(lib, "Winmm.lib")

int main() {
    std::array<char, MAXERRORLENGTH> errorString;
    mciGetErrorStringA(
        mciSendStringA(
            "open \"C:\\path\\to\\1_.mp3\" type mpegvideo alias click1",
            nullptr,
            0,
            nullptr),
        errorString.data(),
        MAXERRORLENGTH);
    std::printf("%s\n", errorString.data());
    mciGetErrorStringA(
        mciSendStringA("play click1", nullptr, 0, nullptr),
        errorString.data(),
        MAXERRORLENGTH);
    std::printf("%s\n", errorString.data());
}

I created a new C++ console application in Visual Studio 2019, built this code, and ran it from the console. It prints:

The specified command was carried out.
The specified command was carried out.

And in my headphones I hear a brief pop, but that's it. What could be happening? Do I first need to configure an audio device? Set the volume?

Upvotes: 0

Views: 420

Answers (1)

selbie
selbie

Reputation: 104494

Your program is ending after you invoke the mci command. The music is going to stop playing when the process exits.

Simply add something to the end of the program to keep it from exiting.

Instead of this:

    std::printf("%s\n", errorString.data());
}

This:

    std::printf("%s\n", errorString.data());
    
    printf("press ctrl-c to exit");
    while (1) {
        Sleep(1000);
    }
}

Upvotes: 2

Related Questions