Search code examples
c#visual-studioaudiomedia-playerdesktop

How to stop sounds with MediaPlayer c#


I have this functions and I must use MediaPlayer because I have to play more sounds together. This code works, but the sounds doesn't stop on the keyup (I tried some code but didn't worked). How can I do the function stopSound? Thank'you!

private void Form1_KeyDown(object sender, KeyPressEventArgs e)
{
    [...]   // Other code
    playSound(key, name);
}

private void Form1_KeyUp(object sender, KeyEventArgs e)
{
    [...]   // Other code
    stopSound(key, name);
}

private void playSound(string name)
{
    [...]   // Other code
    string url = Application.StartupPath + "\\notes\\" + name + ".wav";
    var sound = new System.Windows.Media.MediaPlayer();

    sound.Open(new Uri(url));
    sound.play();
}

private void stopSound(string name)
{
    ???
}

Solution

  • If you store all references to the MediaPlayer instances that you create in a List<MediaPlayer>, you could access them later using this list and stop them. Something like this:

    List<System.Windows.Media.MediaPlayer> sounds = new List<System.Windows.Media.MediaPlayer>();
    private void playSound(string name)
    {
        string url = Application.StartupPath + "\\notes\\" + name + ".wav";
        var sound = new System.Windows.Media.MediaPlayer();
        sound.Open(new Uri(url));
        sound.play();
        sounds.Add(sound);
    }
    
    private void stopSound()
    {
        for (int i = sounds.Count - 1; i >= 0; i--)
        {
            sounds[i].Stop();
            sounds.RemoveAt(i);
        }
    }