Playing multiple wav files in C#

只谈情不闲聊 提交于 2019-12-18 13:42:27

问题


I have an app that I need to play a wav file when a key or button pressed or clicked, I use the SoundPlayer class but when i try to play another wav file at the same time the one that was playing stops.

Is there a way to play multiple wav files at the same time? If its one could you please give me examples or tutorial?

Here's what I got so far:

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!");
        }
    }
}

Thanks!


回答1:


You can do this with the System.Windows.Media.MediaPlayer class. Note that you will need to add references to WindowsBase and 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!");
    }
}

EDIT: You can loop the sound by subscribing to the MediaEnded event.

void MediaPlayer_Loop(object sender, EventArgs e)
{
    MediaPlayer player = sender as MediaPlayer;
    if (player == null)
        return;

    player.Position = new TimeSpan(0);
    player.Play();
}

Based on your code, I'm guessing that you are writing some kind of music production software. I'm honestly not sure that this method will loop perfectly every time, but as far as I can tell, it's the only way to loop using the MediaPlayer control.




回答2:


You cannot play two sounds at once using SoundPlayer.

SoundPlayer uses the Native WINAPI PlaySound which does not support playing multiple sound at same instance.

Better Option would be to Reference WindowsMediaPlayer

Add a reference to 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";


来源:https://stackoverflow.com/questions/15513599/playing-multiple-wav-files-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!