Skip to content

Instantly share code, notes, and snippets.

@zielmicha
Created August 10, 2013 21:06
Show Gist options
  • Save zielmicha/6202137 to your computer and use it in GitHub Desktop.
Save zielmicha/6202137 to your computer and use it in GitHub Desktop.
Emit sounds during typing. sudo python snd.py (list devices) sudo python snd.py /dev/input/<your keyboard> Requires: pip install evdev
from __future__ import division
from math import sin
import math
import sys
import wave
import struct
import subprocess
import os
RATE = 44000
snd_i = 0
tmp_dir = os.path.expanduser('~/.kb_snd')
if not os.path.exists(tmp_dir):
os.mkdir(tmp_dir)
def _play(FREQ, TIME):
global snd_i
snd_i += 1
snd_i %= 10
path = os.path.expanduser(tmp_dir + '/%d.wav' % snd_i)
wav = wave.open(path, 'wb')
wav.setnchannels(1)
wav.setsampwidth(2)
wav.setframerate(RATE)
data = [ math.sin(i/RATE*FREQ) for i in xrange(int(RATE*TIME)) ]
wav.writeframes(''.join( struct.pack('<h', min(1, max(-1, b))*(2**15-1)) for b in data ))
wav.close()
subprocess.Popen(['play', path], stdout=open('/dev/null', 'w'),
stderr=subprocess.PIPE)
from evdev import InputDevice, list_devices, ecodes, categorize
if not sys.argv[1:]:
devices = map(InputDevice, list_devices())
for dev in devices:
print( '%-20s %-32s %s' % (dev.fn, dev.name, dev.phys) )
sys.exit(1)
dev = InputDevice(sys.argv[1])
def play(key):
freq = 4000 + key * 50
_play(freq, 0.1)
for event in dev.read_loop():
if event.type == ecodes.EV_KEY:
if event.value == 1:
play(event.code)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment