#include <windows.h>
#include <mmsystem.h>
#include <iostream>
#include <string>
// 链接winmm库(Dev-C++需确认已添加 -lwinmm)
#pragma comment(lib, "winmm.lib") 
// 错误处理函数:打印MCI错误信息
void printMciError(MCIERROR errCode, const std::string& action) {
    char errMsg[256] = {0};
    mciGetErrorString(errCode, errMsg, sizeof(errMsg));
    std::cerr << "错误:" << action << " 失败!" << std::endl;
    std::cerr << "错误码:" << errCode << " | 错误信息:" << errMsg << std::endl;
}
// 音频播放函数
bool playWavAudio(const std::string& audioPath) {
    // 拼接MCI命令(C++ string 拼接更安全)
    std::string openCmd = "open \"" + audioPath + "\" type waveaudio alias myAudio";   
    // 打印实际执行的命令(调试用)
    std::cout << "执行命令:" << openCmd << std::endl;
    // 打开音频文件
    MCIERROR err = mciSendStringA(openCmd.c_str(), NULL, 0, NULL);
    if (err != 0) {
        printMciError(err, "打开音频文件");
        return false;
    }
    // 播放音频(wait:等待播放完成)
    err = mciSendStringA("play myAudio wait", NULL, 0, NULL);
    if (err != 0) {
        printMciError(err, "播放音频");
        mciSendStringA("close myAudio", NULL, 0, NULL); // 清理资源
        return false;
    }
    // 关闭音频设备
    err = mciSendStringA("close myAudio", NULL, 0, NULL);
    if (err != 0) {
        printMciError(err, "关闭音频设备");
        return false;
    }

    return true;
}
int main() {
    std::string audioPath = "MontagemXonada.wav";

    // 播放音频
    if (playWavAudio(audioPath)) {
        std::cout << "\n音频播放完成!" << std::endl;
    } else {
        std::cout << "\n音频播放失败,请检查路径/文件!" << std::endl;
    }
    // 暂停控制台,避免闪退(Dev-C++专用)
    system("pause");
    return 0;
}

0 条评论

目前还没有评论...