//文件路径
public static string path = AppDomain.CurrentDomain.BaseDirectory + @"..\..\sound\";
#region 调用AP函数I播放音乐,要用到 mciSendString
/// <summary>
/// 播放MP3格式的音频文件方法
/// </summary>
/// <param name="lpstrCommand"></param>
/// <param name="lpstrReturnString"></param>
/// <param name="uReturnLength"></param>
/// <param name="hwndCallback"></param>
/// <returns></returns>
[DllImport("winmm.dll", EntryPoint = "mciSendString", CharSet = CharSet.Auto)]
public static extern int mciSendString(
string lpstrCommand,//Pointer to a null-terminated string that specifies an MCI command string. For a list, see Multimedia Command Strings.
string lpstrReturnString,//Pointer to a buffer that receives return information. If no return information is needed, this parameter can be NULL.
int uReturnLength,//Size, in characters, of the return buffer specified by the lpszReturnString parameter.
int hwndCallback);//Handle to a callback window if the "notify" flag was specified in the command string.
/// <summary>
/// 播放MID格式音频的方法
/// </summary>
/// <param name="lpstrCommand"></param>
/// <param name="lpstrReturnString"></param>
/// <param name="uReturnLength"></param>
/// <param name="hwndCallback"></param>
/// <returns></returns>
[DllImport("winmm.dll", EntryPoint = "mciSendString", CharSet = CharSet.Auto)]
public static extern long mciExecute(
string lpstrCommand,//Pointer to a null-terminated string that specifies an MCI command string. For a list, see Multimedia Command Strings.
string lpstrReturnString,//Pointer to a buffer that receives return information. If no return information is needed, this parameter can be NULL.
int uReturnLength,//Size, in characters, of the return buffer specified by the lpszReturnString parameter.
int hwndCallback);//Handle to a callback window if the "notify" flag was specified in the command string.
#endregion
#region mp3和mid文件的播放方法
/// <summary>
/// 背景音乐播放方法
/// </summary>
/// <param name="path"></param>
private void playMID(string path)
{
mciExecute("Open " + path + " alias mid", null, 0, 0);
mciExecute("Play mid", null, 0, 0);
}
/// <summary>
/// 背景音乐停止方法
/// </summary>
private void pauseMID()
{
mciExecute("Close mid", null, 0, 0);
}
public void playWAV(string path)
{
mciSendString("Open " + path + " alias wavType", null, 0, 0);
mciSendString("Play wavType", null, 0, 0);
}
public void pauseWAV()
{
mciSendString("Close wavType", null, 0, 0);
}
#endregion
//在窗体加载事件里调用上面的两个方法来播放mp3和mid
private void Form1_Load(object sender, EventArgs e)
{
this.playMID(path + "back2.mid");
this.playWAV(path + "back.mp3");//此方法也可以播放WAV格式音频文件
}