Reputation: 71
So I'm working on a rhythm trainer, and using wxpython as the UI Toolkit. I was wondering if anyone knew how to bind keyboard presses to play sounds? So to put it simply, users can use the keyboard to play a drum beat. Example "Pressing the A key will play the bass drum"
Now I've come across a tutorial -
http://www.blog.pythonlibrary.org/2009/08/29/wxpython-catching-key-and-char-events/
But this seems like it needs the button to successfully play the sound. I've got a bit of the functionality working using this example. But I was wondering if there's another way to do it without the need of a button?
import wx
class MyForm(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, wx.ID_ANY, "Key Press Tutorial")
# Add a panel so it looks the correct on all platforms
panel = wx.Panel(self, wx.ID_ANY)
btn = wx.Button(panel, label="OK")
btn.Bind(wx.EVT_KEY_DOWN, self.onKeyPress)
def onKeyPress(self, event):
keycode = event.GetKeyCode()
print keycode
if keycode == ord('A'):
print "you pressed the spacebar!"
sound_file = "notation1.wav"
sound=wx.Sound(sound_file)
print(sound_file)
sound.Play(wx.SOUND_ASYNC)
event.Skip()
# Run the program
if __name__ == "__main__":
app = wx.PySimpleApp()
frame = MyForm()
frame.Show()
app.MainLoop()
This is my example using the tutorial.
Cheers!
Upvotes: 0
Views: 5270
Reputation: 33071
My tutorial is about catching keystrokes on the widget that's in focus. In the case of the tutorial, that was the button that was in focus and that was why it was bound to EVT_KEY_DOWN. Sadly, panels don't really accept focus very easily, so you'll be better off to set the focus on the panel manually using SetFocus() or bind the key event to most of the widgets.
You might be able to use an AcceleratorTable, but I'm not sure if that will work in your situation. Here's a link to a tutorial on that topic though:
http://www.blog.pythonlibrary.org/2010/12/02/wxpython-keyboard-shortcuts-accelerators/
Upvotes: 1