Advertisement
pantteri

Funny instrument (MacBook only)

Feb 18th, 2013
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.72 KB | None | 0 0
  1. #!/usr/bin/env python
  2.  
  3. import array
  4. import math
  5. import time
  6. from threading import Thread
  7.  
  8. import pyaudio
  9. import applesms
  10.  
  11.  
  12.  
  13. class Sine:
  14.  
  15.     def __init__(self, hz, amplitude=1, rate=44100):
  16.         self.hz = hz
  17.         self.rate = rate
  18.         self.amp = amplitude
  19.  
  20.     def value(self, frame):
  21.         return self.amp * math.sin(math.pi * 2 * self.hz * frame / self.rate)
  22.  
  23.  
  24.  
  25. class Audio(Thread):
  26.  
  27.     def __init__(self):
  28.         Thread.__init__(self)
  29.  
  30.         self.rate = 44100
  31.         self.sounds = []
  32.         self.stopped = False
  33.         self.samples = 100
  34.         self.frame = 0
  35.         self.volume = 1.0
  36.         self.tempo = 120
  37.        
  38.         self.p = pyaudio.PyAudio()
  39.         self.stream = self.p.open(rate=self.rate,
  40.                 channels=1, format=pyaudio.paFloat32, output=True)
  41.  
  42.     def run(self):
  43.         while not self.stopped:
  44.             try:
  45.                 self.stream.write(array.array('f',
  46.                         (self._amp() for _ in range(self.samples))).tostring())
  47.             except IOError:
  48.                 break
  49.  
  50.     def _amp(self): # amplitude
  51.         self.frame += 1
  52.         return sum([i.value(self.frame) for i in self.sounds]) * self.volume
  53.  
  54.     def add(self, instrument):
  55.         self.sounds.append(instrument)
  56.  
  57.     def remove(self, index):
  58.         del self.sounds[index]
  59.        
  60.     def stop(self):
  61.         self.stopped = True
  62.         self.stream.close()
  63.         self.p.terminate()
  64.  
  65.  
  66.  
  67. if __name__ == '__main__':
  68.     a = Audio()
  69.     sine = Sine(300)
  70.     a.add(sine)
  71.     a.start()
  72.  
  73.     try:
  74.         while True:
  75.             (x, y, z) = applesms.coords()
  76.             sine.hz = 300 + z
  77.             time.sleep(0.05)
  78.  
  79.     finally:
  80.         a.stop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement