毫无疑问,c++本身无法播放声音。在windows下可以借助mci(媒体控制接口)播放MP3资源,并且很好的控制播放对象。如果你是C++新人,想写一个控制台下播放mp3的小程序,那么本文完全适合你。<p></p><p>调用mci一般要借助mciSendString函数,使用该函数需要包含头文件 然而这样一来就会依赖整个mfc框架,导致普通的控制台程序根本无法编译(其实是链接不过去)。所以我在下面的代码中直接从系统的 中调用函数,即使用LoadLibraryA("") 。C++新人可能不懂这些,没关系,你只要知道我的代码可以直接贴到你的控制台程序中去就行了。</p><p>文件</p><p></p><pre name="code" class="cpp">#include<string>
<pre name="code" class="cpp">#include<>
typedef int(__stdcall* w32mci)(const char*, char*, int, int);
typedef int(__stdcall * w32mcierror)(int, char*, int);
class Mci
{
private:
HINSTANCE hins;
w32mci wmci;
w32mcierror wmcierror;
public:
Mci();
~Mci();
char buf[256];
bool send(std::string command);//error return false
};
class AudioClip
{
private:
Mci mci;
std::string filename;
std::string alias;
int length_ms;
public:
AudioClip();
~AudioClip();
bool load(const std::string& _filename);
bool play(int start_ms=0, int end_ms=-1);
bool stop();
bool pause();
bool unpause();
int milliseconds();
};
实现文件:
<pre name="code" class="cpp">#include"audio_clip.h"
#include<iostream>
#include<random>
#include<>
Mci::Mci()
{
HINSTANCE hins = LoadLibraryA("");
wmci=(w32mci)GetProcAddress(hins, "mciSendStringA");
wmcierror = (w32mcierror)GetProcAddress(hins, "mciGetErrorStringA");
}
Mci::~Mci()
{
FreeLibrary(hins);
}
bool Mci::send(std::string command)
{
int errcode = wmci(command.c_str(), buf, 254, 0);
if (errcode)
{
wmcierror(errcode, buf, 254);
return false;
}
return true;
}
AudioClip::AudioClip()
{
//do nothing
}
AudioClip::~AudioClip()
{
std::string cmd;
cmd = "close " + alias;
(cmd);
}
bool AudioClip::load(const std::string& _filename)
{
filename = _filename;
for (unsigned int i = 0; i < (); i++)
{
if (filename[i] == '/')
filename[i] = '\\';
}
alias = "mp3_";
srand(time(NULL));
char randstr[6];
_itoa(rand() % 65536, randstr, 10);
(randstr);
std::string cmd;
cmd = "open " + filename + " alias " + alias;
if ((cmd) == false)
return false;
cmd = "set " + alias + " time format milliseconds";
if ((cmd) == false)
return false;
cmd = "status " + alias + " length";
if ((cmd) == false)
return false;
length_ms = atoi();
return true;
}
bool AudioClip::play(int start_ms , int end_ms)
{
if (end_ms == -1) end_ms = length_ms;
std::string cmd;
char start_str[16], end_str[16];
_itoa(start_ms, start_str,10);
_itoa(end_ms, end_str, 10);
cmd = "play " + alias+" from ";
(start_str);
(" to ");
(end_str);
return (cmd);
}
bool AudioClip::stop()
{
std::string cmd;
cmd = "stop "+alias;
if ((cmd) == false)
return false;
cmd = "seek " + alias + " to start";
if ((cmd) == false)
return false;
return true;
}
bool AudioClip::pause()
{
std::string cmd;
cmd = "pause " + alias;
if ((cmd) == false)
return false;
return true;
}
bool AudioClip::unpause()
{
std::string cmd;
cmd = "resume " + alias;
if ((cmd) == false)
return false;
return true;
}
int AudioClip::milliseconds()
{
return length_ms;
}
代码就这么多,在你的代码中这样做就可以播放了
#include"audio_clip.h"
int main()
{
AudioClip ac;
("D:/****.mp3");
();
system("pause");
}