在C#中播放多个wav文件

时间:2013-03-20 01:17:55

标签: c# winforms audio wav

我有一个应用程序,当按下或单击按键或按钮时,我需要播放一个wav文件,我使用SoundPlayer类,但是当我尝试播放另一个wav文件时,正在播放的文件停止。< / p>

有没有办法同时播放多个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!");
        }
    }
}

谢谢!

2 个答案:

答案 0 :(得分:9)

您可以使用System.Windows.Media.MediaPlayer课程执行此操作。请注意,您需要添加对WindowsBasePresentationCore的引用。

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控件的唯一方法。

答案 1 :(得分:0)

无法使用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";
相关问题