本文以实例介绍了C#如何通过winmm.dll来播放声音,主要实现步骤如下:
1.首先导入如下两个函数:
////// 向媒体控制接口发送控制命令 /// /// 命令,参见 /// http://msdn.microsoft.com/en-us/library/windows/desktop/dd743572(v=vs.85).aspx /// 命令返回的信息,如果没有需要返回的信息可以为null /// 指定返回信息的字符串大小 /// 回调句柄,如果命令参数中没有指定notify标识,可以为new IntPtr(0) ///返回命令执行状态的错误代码 [Dllimport("winmm.dll")] static extern Int32 mciSendString(string lpszCommand, StringBuilder returnString, int bufferSize, IntPtr hwndCallback); ////// 返回对执行状态错误代码的描述 /// /// mciSendCommand或者mciSendString返回的错误代码 /// 对错误代码的描述字符串 /// 指定字符串的大小 ///如果ERROR Code未知,返回false [Dllimport("winmm.dll")] static extern bool mciGetErrorString(Int32 errorCode, StringBuilder errorText, Int32 errorTextSize);
2.示例代码如下:
int error = mciSendString("open C:\Users\Angel\Desktop\123.wav alias myDivece", null, 0, new IntPtr(0));
if (error == 0)
{
mciSendString("play myDivece", null, 0, new IntPtr(0)); //播放
}
else
{
StringBuilder errorText = new StringBuilder();
mciGetErrorString(error, errorText, 50);
MessageBox.Show(errorText.ToString());
}
3.可以通过以下语句进行播放控制:
mciSendString("play myDivece", null, 0, new IntPtr(0)); //播放
mciSendString("pause myDivece", null, 0, new IntPtr(0)); //暂停
mciSendString("stop myDivece", null, 0, new IntPtr(0)); //停止
mciSendString("close myDivece", null, 0, new IntPtr(0)); //关闭
感兴趣的读者可以动手测试一下本文实例,相信会对大家的C#程序设计起到一定的借鉴与帮助作用。



