简体   繁体   中英

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)
{
    ???
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM