我有这个功能,我必须使用MediaPlayer,因为我必须一起播放更多声音。这段代码有效,但声音并没有停留在密钥上(我尝试了一些代码,但没有工作)。我该怎么做函数stopSound? 谢谢'你
!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)
{
???
}
答案 0 :(得分:1)
如果您存储了对在MediaPlayer
中创建的List<MediaPlayer>
个实例的所有引用,则可以稍后使用此列表访问它们并停止它们。像这样:
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);
}
}