用c++语言写一段完整可直接运行代码,播放名为“hit.mp3”的音乐
时间: 2024-02-29 10:52:04 浏览: 17
为了播放音乐,我们需要使用第三方库,例如Windows平台下的MCI库。以下是使用MCI库播放音乐的C++代码示例:
```c++
#include <iostream>
#include <windows.h>
#include <mmsystem.h>
#pragma comment(lib, "winmm.lib")
int main() {
std::string musicPath = "hit.mp3";
MCI_OPEN_PARMS mciOpenParms;
mciOpenParms.lpstrDeviceType = "mpegvideo";
mciOpenParms.lpstrElementName = musicPath.c_str();
DWORD dwReturn;
if (mciSendCommand(NULL, MCI_OPEN, MCI_OPEN_TYPE | MCI_OPEN_ELEMENT, (DWORD)(LPVOID)&mciOpenParms)) {
std::cout << "Failed to open music file: " << musicPath << std::endl;
return 1;
}
DWORD_PTR dwID = mciOpenParms.wDeviceID;
MCI_PLAY_PARMS mciPlayParms;
if (mciSendCommand(dwID, MCI_PLAY, 0, (DWORD)(LPVOID)&mciPlayParms)) {
std::cout << "Failed to play music file: " << musicPath << std::endl;
mciSendCommand(dwID, MCI_CLOSE, 0, NULL);
return 1;
}
std::cout << "Playing music file: " << musicPath << std::endl;
std::cout << "Press any key to stop." << std::endl;
std::cin.get();
mciSendCommand(dwID, MCI_STOP, 0, NULL);
mciSendCommand(dwID, MCI_CLOSE, 0, NULL);
return 0;
}
```
在本例中,我们使用了`mciSendCommand`函数来发送命令给MCI设备,并播放名为“hit.mp3”的音乐文件。需要注意的是,本例中使用的MCI命令仅适用于Windows平台。
你可以将本代码保存为`main.cpp`文件,并使用Visual Studio等工具编译运行。记得将音乐文件放在与可执行文件相同的目录下。