问题
i would like to play a sound in C# while the key is down. If the key is released the sounds automatically stops.
This is what I have so far:
var player = new System.Windows.Media.MediaPlayer();
try
{
player.Open(new Uri(label46.Text));
player.Volume = (double)trackBar4.Value / 100;
player.Play();
}
catch (FileNotFoundException)
{
MessageBox.Show("File has been moved." + "\n" + "Please relocate it now!");
}
回答1:
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;
}
回答2:
http://msdn.microsoft.com/en-us/library/system.windows.input.keyboard.aspx
This class fires events when the keyboard changes state, you can subscribe to the events and then check if the key pressed is the key you want.
For example, in the KeyDown event, check to see if they key is "P" or whatever, if it is, Play your file. On the KeyUp event, check to see if they key is the same key, then stop playing your file.
This example is not exactly what you need but it should get you started :
private void OnKeyDownHandler(object sender, KeyEventArgs e)
{
if (e.Key == Key.Return)
{
textBlock1.Text = "You Entered: " + textBox1.Text;
}
}
来源:https://stackoverflow.com/questions/16702659/play-a-sound-while-key-is-down