You can handle this through KeyDown and KeyUp events. For this, both events needs to know your Media Object and playing status. There might be other possibilities which I am not aware. I have used this senerio for playing and recording. You may try for playing only.
Secondly, you also need to reset if the key is pressed contineously even after media ended or failed. So, you need to register these events and do the same actions as you do in KeyUP event.
Example below shows Application Window's KeyUP and KeyDown events.
MediaPlayer player = new System.Windows.Media.MediaPlayer();
bool playing = false;
private void Window_KeyDown(object sender, KeyEventArgs e)
{
if (playing == true)
{
return;
}
/* your code follows */
try
{
player.Open(new Uri(label46.Text));
player.Volume = (double)trackBar4.Value / 100;
player.Play();
playing = true;
}
catch (FileNotFoundException)
{
MessageBox.Show("File has been moved." + "\n" + "Please relocate it now!");
}
}
private void Window_KeyUp(object sender, KeyEventArgs e)
{
if (playing == false)
{
return;
}
/* below code you need to copy to your Media Ended/Media Failed events */
player.Stop();
player.Close();
playing = false;
}