简体   繁体   中英

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?

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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM