//文件路徑
public static string path = AppDomain.CurrentDomain.BaseDirectory + @"..\..\sound\";
#region 調(diào)用AP函數(shù)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
//在窗體加載事件里調(diào)用上面的兩個(gè)方法來播放mp3和mid
private void Form1_Load(object sender, EventArgs e)
{
this.playMID(path + "back2.mid");
this.playWAV(path + "back.mp3");//此方法也可以播放WAV格式音頻文件
}