这是我的代码:
MediaPlayer player = new System.Windows.Media.MediaPlayer();
bool playing = false;
bool _bKeyIsDown = false;
protected override void OnKeyDown(KeyEventArgs e)
{
if (_bKeyIsDown) return;
_bKeyIsDown = true;
// play sound;
base.OnKeyDown(e);
}
protected override void OnKeyUp(KeyEventArgs e)
{
base.OnKeyUp(e);
_bKeyIsDown = false;
}
private void Window_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.D1)
{
if (label5.Text == "Waiting 01.wav")
{
MessageBox.Show("No beat loaded");
return;
}
pictureBox6.Image = Form1.Properties.Resources.white_square_button;
try
{
playing = true;
player.Open(new Uri(label37.Text));
player.Volume = (double)trackBar4.Value / 100;
player.Play();
}
catch (FileNotFoundException)
{
MessageBox.Show("File has been moved." + "\n" + "Please relocate it now!");
}
}
}
private void Window_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.D1)
{
pictureBox6.Image = Form1.Properties.Resources.black_square_button;
player1.Stop();
player1.Close();
playing = false;
}
这使得在按键关闭时发出声音,但问题是,当您释放该按键并按另一个按键时,声音会延迟,如果您同时按下2个按键,它只播放第一个按键按压。
如果您删除(_bKeyIsDown) return;
,它就可以完成,但声音不会全长播放。
有没有办法解决这个问题?谢谢!
答案 0 :(得分:0)
如果只是播放并停止1声音,只需执行KeyDown事件并使用bool切换:
bool playing = false;
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.D1)
{
if (!playing)
{
player.Open(new Uri(yourURI));
player.Play();
playing = true;
}
else
{
player.Stop();
playing = false;
}
}
}
编辑:
那么我可以建议你创建一个包含你需要的所有声音的字典:
Dictionary<Keys, Uri> sounds = new Dictionary<Keys, Uri>()
{
{Keys.A,new Uri(@"C:\..\..\youraudiofile.mp3")},
{Keys.B,new Uri(@"C:\..\yourotheraudiofile.wma")}
};
并创建一个列表以保留对媒体播放器的引用:
List<MediaPlayer> myplayers = new List<MediaPlayer>();
然后只在KeyDown事件中(删除onKeyDown和keyup):
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
foreach (MediaPlayer m in myplayers)
{
m.Stop();
}
return;
}
if (sounds.ContainsKey(e.KeyCode))
{
MediaPlayer mp = new MediaPlayer();
mp.Open(sounds[e.KeyCode]);
mp.Play();
}
}