简体   繁体   English

如何使用MediaPlayer C#停止声音

[英]How to stop sounds with MediaPlayer c#

I have this functions and I must use MediaPlayer because I have to play more sounds together. 我具有此功能,并且必须使用MediaPlayer,因为我必须一起播放更多声音。 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. 如果将对创建的MediaPlayer实例的所有引用存储在List<MediaPlayer> ,则可以稍后使用此列表访问它们并停止它们。 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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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