在C#中播放多个wav文件
我有一个应用程序,当按下或单击一个键或按钮时我需要播放一个wav文件,我使用SoundPlayer类,但当我尝试播放另一个wav文件同时正在播放的那个文件停止。
有没有办法同时播放多个wav文件? 如果它可以请你给我举例或教程?
这是我到目前为止所得到的:
private void pictureBox20_Click(object sender, EventArgs e) { if (label30.Text == "Waiting 15.wav") { MessageBox.Show("No beat loaded"); return; } using (SoundPlayer player = new SoundPlayer(label51.Text)) { try { player.Play(); } catch (FileNotFoundException) { MessageBox.Show("File has been moved." + "\n" + "Please relocate it now!"); } } }
谢谢!
您可以使用System.Windows.Media.MediaPlayer
类执行此操作。 请注意,您需要添加对WindowsBase
和PresentationCore
引用。
private void pictureBox20_Click(object sender, EventArgs e) { const bool loopPlayer = true; if (label30.Text == "Waiting 15.wav") { MessageBox.Show("No beat loaded"); return; } var player = new System.Windows.Media.MediaPlayer(); try { player.Open(new Uri(label51.Text)); if(loopPlayer) player.MediaEnded += MediaPlayer_Loop; player.Play(); } catch (FileNotFoundException) { MessageBox.Show("File has been moved." + "\n" + "Please relocate it now!"); } }
编辑:您可以通过订阅MediaEnded
事件来循环播放声音。
void MediaPlayer_Loop(object sender, EventArgs e) { MediaPlayer player = sender as MediaPlayer; if (player == null) return; player.Position = new TimeSpan(0); player.Play(); }
根据你的代码,我猜你正在编写某种音乐制作软件。 老实说,我不确定这种方法每次都会完美循环,但据我所知,这是循环使用MediaPlayer控件的唯一方法。
使用SoundPlayer 无法一次播放两种声音。
SoundPlayer使用Native WINAPI PlaySound
,它不支持在同一个实例中播放多个声音。
更好的选择是参考WindowsMediaPlayer
添加对C:\Windows\System32\wmp.dll
var player1 = new WMPLib.WindowsMediaPlayer(); player1.URL = @"C:\audio_output\sample1.wav"; var player2 = new WMPLib.WindowsMediaPlayer(); player2.URL = @"C:\audio_output\sample2.wav";