【问题标题】:Play a tone while key is down C#按下键时播放音调C#
【发布时间】:2016-03-12 15:43:44
【问题描述】:

我正在构建一个钢琴控制台应用程序,它会在特定时间段内以特定频率播放哔声/音调。帮助 最终只要按下该键就会播放音调。 P.S 最终会同时播放几个音调

namespace something
{

 public class piano
 {

  [DllImport("kernel32.dll")]
  static extern bool Beep(uint dwFreq, uint dwDuration);

  public static void  Main (string [] args)
    {

     Console.WriteLine("This is a piano.");

  //The following code is wrong but you get the idea
     char x = KeyDown;
     switch(x)

     case "q":
     Beep(523,500);
     break;

     case "w":
     Beep(587,500);
     break;

     //etc

     default:
     break;
   }
  }
 }

【问题讨论】:

  • 你的问题到底是什么??

标签: c# keypress keydown beep


【解决方案1】:

在控制台应用程序中,您可以检测到某个键何时被按下,但不能检测到它何时被释放。因此我会使用 WinForms 应用程序。

在 WinForms 表单中,您可以在表单级别使用 KeyDownKeyUp 事件。为了激活它们,您必须将表单的KeyPreview 属性设置为true。您可以在属性窗口或代码中执行此操作。

那么你必须记住按下了哪些键。我为此使用了HashSet<Keys>

// Stores the keys in pressed state.
private HashSet<Keys> _pressedKeys = new HashSet<Keys>();

// Used in DisplayKeys method.
private StringBuilder _sb = new StringBuilder();

// Form constructor
public frmKeyboard()
{
    InitializeComponent();
    KeyPreview = true; // Activate key preview at form level.
}

private void frmKeyboard_KeyDown(object sender, KeyEventArgs e)
{
    // Each time a key is pressed, add it to the set of pressed keys.
    _pressedKeys.Add(e.KeyCode);
    DisplayKeys();
}

private void frmKeyboard_KeyUp(object sender, KeyEventArgs e)
{
    // Each time a key is released, remove it from the set of pressed keys.
    _pressedKeys.Remove(e.KeyCode);
    DisplayKeys();
}

private void DisplayKeys()
{
    _sb.Clear();
    foreach (Keys key in _pressedKeys.OrderBy(k => k)) {
        _sb.AppendLine(key.ToString());
    }
    label1.Text = _sb.ToString();
}

现在,您可以一次按一个或多个键,它们将显示在一个标签中。


简单的Beep 方法不会让您同时播放声音。有关可能的解决方案,请参阅 MSDN 上的此线程:Playing Sounds Simultaneously。另一种选择可能是MIDI.NET

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-05
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    相关资源
    最近更新 更多