Listen for key events and play a tone based on its value.
| 9 | |
| 10 | |
| 11 | class KeyboardXylophone: |
| 12 | """Listen for key events and play a tone based on its value.""" |
| 13 | |
| 14 | def __init__( |
| 15 | self, duration_ms: int = 250, volume: float = 0.1, freq_mul: int = 10 |
| 16 | ) -> None: |
| 17 | self._boombox = BoomBox("") |
| 18 | self.duration_ms = duration_ms |
| 19 | self.volume = volume |
| 20 | self.freq_mul = freq_mul |
| 21 | |
| 22 | def play_sound(self, frequency: float): |
| 23 | """Play sound at given frequency.""" |
| 24 | self._boombox.play_tone(frequency, self.duration_ms, self.volume) |
| 25 | |
| 26 | def on_press(self, key): |
| 27 | """Play sound on key press.""" |
| 28 | try: |
| 29 | self.play_sound(ord(key.char) * self.freq_mul) |
| 30 | except AttributeError: |
| 31 | pass |
| 32 | |
| 33 | def on_release(self, key): |
| 34 | """Return False if Escape is released.""" |
| 35 | if key == keyboard.Key.esc: |
| 36 | return False |
| 37 | |
| 38 | def run(self): |
| 39 | """Start listening for key events.""" |
| 40 | with keyboard.Listener( |
| 41 | on_press=self.on_press, on_release=self.on_release |
| 42 | ) as listener: |
| 43 | listener.join() |
| 44 | |
| 45 | |
| 46 | if __name__ == "__main__": |