Skip to content

Instantly share code, notes, and snippets.

@blacklight
Created October 27, 2013 03:22
Show Gist options
  • Save blacklight/7177654 to your computer and use it in GitHub Desktop.
Save blacklight/7177654 to your computer and use it in GitHub Desktop.
Python script for using your Leap Motion as a weird theremin. Requirements: Leap SDK, pyaudio and numpy
#!/usr/bin/python
import sys
import math
import pyaudio
import numpy
import Leap
from datetime import datetime
class SoundDriver(object):
def __init__(self, rate=44100):
self.pyaudio = pyaudio.PyAudio()
self.rate = rate
@staticmethod
def sin(frequency, length, rate):
length = int(length * rate)
factor = float(frequency) * (math.pi * 2) / rate
return numpy.sin(numpy.arange(length) * factor)
def initialize(self):
self.stream = self.pyaudio.open(
format = pyaudio.paFloat32,
channels = 1,
rate = self.rate,
output = True)
def playFrequency(self, frequency, amplitude = 1, length = 1):
chunks = []
chunks.append(SoundDriver().sin(frequency, length, self.rate))
chunk = numpy.concatenate(chunks) * amplitude
self.stream.write(chunk.astype(numpy.float32).tostring())
def close(self):
self.stream.stop_stream()
self.stream.close()
self.pyaudio.terminate()
class SampleListener(Leap.Listener):
def hook_sound_driver(self, sound_driver):
self.sound_driver = sound_driver
def on_init(self, controller):
print "Initialized"
self.prev_value = -1
def on_connect(self, controller):
print "Connected"
def on_disconnect(self, controller):
print "Disconnected"
def on_exit(self, controller):
print "Exited"
def on_frame(self, controller):
frame = controller.frame()
if not frame.hands.empty:
for i in range(0, len(frame.hands)):
hand = frame.hands[i]
y = hand.palm_position[1]
frequency = SampleListener().yToFreq(y)
self.sound_driver.playFrequency(frequency, 1, 0.0689)
# self.sound_driver.playFrequency(frequency, 1, 0.00089)
print "Hand %d height: %f - Frequency: %f" % (i, y, frequency)
@staticmethod
def yToFreq(y):
yMinHeight = 40
yMaxHeight = 700
minFreq = 20
maxFreq = 20000
y -= yMinHeight
yMaxHeight -= yMinHeight
maxFreq -= minFreq
frequency = minFreq + ((maxFreq*y) / yMaxHeight)
if frequency < minFreq:
return minFreq
if frequency > maxFreq:
return maxFreq
return frequency
# return maxFreq - frequency
def main():
sound = SoundDriver()
sound.initialize()
listener = SampleListener()
listener.hook_sound_driver(sound)
controller = Leap.Controller()
controller.add_listener(listener)
print "Press Enter to quit..."
sys.stdin.readline()
controller.remove_listener(listener)
sound.close()
if __name__ == "__main__":
main()
@Extraltodeus
Copy link

if you replace "if not frame.hands.empty:"
by "if frame.is_valid:"
then it works

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment