here is my code:
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;
}
This what makes is to play a sound while key is down, but the problem is that when you release that key and press another one the sound delays and if you press 2 keys at the same time it only play the first one you pressed.
If you remove if (_bKeyIsDown) return;
it does the trick but the sound won't play at its full length.
Is there a way to fix this problem? Thanks!