介绍如何通过winmm.dll播放声音
首先导入两个函数
/// <summary> /// 向媒体控制接口发送控制命令 /// </summary> /// <param name="lpszCommand">命令,参见 /// http://msdn.microsoft.com/en-us/library/windows/desktop/dd743572(v=vs.85).aspx </param> /// <param name="lpszReturnString">命令返回的信息,如果没有需要返回的信息可以为null</param> /// <param name="cchReturn">指定返回信息的字符串大小</param> /// <param name="hwndCallback">回调句柄,如果命令参数中没有指定notify标识,可以为new IntPtr(0)</param> /// <returns>返回命令执行状态的错误代码</returns> [DllImport("winmm.dll")] static extern Int32 mciSendString(string lpszCommand, StringBuilder returnString, int bufferSize, IntPtr hwndCallback); /// <summary> /// 返回对执行状态错误代码的描述 /// </summary> /// <param name="errorCode">mciSendCommand或者mciSendString返回的错误代码</param> /// <param name="errorText">对错误代码的描述字符串</param> /// <param name="errorTextSize">指定字符串的大小</param> /// <returns>如果ERROR Code未知,返回false</returns> [DllImport("winmm.dll")] static extern bool mciGetErrorString(Int32 errorCode, StringBuilder errorText, Int32 errorTextSize);
示例代码
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()); }
可以通过以下语句进行播放控制
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)); //关闭