C#.NET7 多线程播放mp3/wav音频|winmm.dll winapi播放音乐文件
测试
C# 全选
var filePath = Path.Combine(System.Windows.Forms.Application.StartupPath, @"sound\歌曲.wav");
//播放系统声音:多线程可正常播放
System.Media.SystemSounds.Beep.Play();
Thread.Sleep(1000);
//播放wav/mp3声音文件:多线程可正常播放
MySoundPlayer.PlayMusic(filePath);
MySoundPlayer.StopMusic(filePath);
//播放wav/mp3声音文件:多线程播放无效,单线程有效
System.Windows.Media.MediaPlayer mr = new System.Windows.Media.MediaPlayer();
mr.Open(new Uri(filePath));
mr.Play();
mr.Close();
MySoundPlayer/ 使用 winmm.dll winapi播放音乐文件
C# 全选
public class MySoundPlayer
{
public static uint SND_ASYNC = 0x0001;
public static uint SND_FILENAME = 0x00020000;
[DllImport("winmm.dll")]
public static extern uint mciSendString(string lpstrCommand, string lpstrReturnString, uint uReturnLength, uint hWndCallback);
public static void PlayNmusinc(string path)
{
mciSendString(@"close temp_alias", null, 0, 0);
mciSendString(@"open """ + path + @""" alias temp_alias", null, 0, 0);
mciSendString("play temp_alias repeat", null, 0, 0);
}
/// <summary>
/// 播放音乐文件(重复)
/// </summary>
/// <param name="p_FileName">音乐文件名称</param>
public static void PlayMusic_Repeat(string p_FileName)
{
try
{
mciSendString(@"close temp_music", " ", 0, 0);
mciSendString(@"open " + p_FileName + " alias temp_music", " ", 0, 0);
mciSendString(@"play temp_music repeat", " ", 0, 0);
}
catch
{ }
}
/// <summary>
/// 播放音乐文件
/// </summary>
/// <param name="p_FileName">音乐文件名称</param>
public static void PlayMusic(string p_FileName)
{
try
{
mciSendString(@"close temp_music", " ", 0, 0);
//mciSendString(@"open " + p_FileName + " alias temp_music", " ", 0, 0);
mciSendString(@"open """ + p_FileName + @""" alias temp_music", null, 0, 0);
mciSendString(@"play temp_music", " ", 0, 0);
}
catch
{ }
}
/// <summary>
/// 停止当前音乐播放
/// </summary>
/// <param name="p_FileName">音乐文件名称</param>
public static void StopMusic(string p_FileName)
{
try
{
mciSendString(@"close " + p_FileName, " ", 0, 0);
}
catch { }
}
}
版权声明:本文为开发框架文库发布内容,转载请附上原文出处连接
NewDoc C/S框架网