#INITIALIZATION.PY
class MicrophoneStream:
	def __init__(self):
		import numpy
		import pyaudio
		import sys
		
		self.chunk = 512
		FORMAT = pyaudio.paInt16
		CHANNELS = 2
		RATE = 44100
		
		if sys.platform == 'darwin':
			CHANNELS = 1
		
		self.p = pyaudio.PyAudio()
		
		self.stream = self.p.open(format = FORMAT,
                channels = CHANNELS,
                rate = RATE,
                input = True,
                frames_per_buffer = self.chunk)

		print("Microphone input stream opened.")

	def __del__(self):
		self.stream.stop_stream()
		self.stream.close()
		self.p.terminate()
		
		print("Microphone input stream closed.")

from bge import logic
cont = bge.logic.getCurrentController()
own = cont.owner
if not 'init' in own:		
	bge.logic.micStream = MicrophoneStream()
	own['init'] = 1
	
#APPLYMICDATA.PY
from bge import logic

cont = bge.logic.getCurrentController()
own = cont.owner

if 'init' in own:

	def getAmplitude(streamName):	
		import numpy 
		import analyse
		
		data = streamName.stream.read(streamName.chunk)
		samps = numpy.fromstring(data, dtype=numpy.int16)
		return analyse.loudness(samps)
	def getPitch(streamName):
		import numpy 
		import analyse
		
		data = streamName.stream.read(streamName.chunk)
		samps = numpy.fromstring(data, dtype=numpy.int16)
		return analyse.musical_detect_pitch(samps)
	
	own['amplitude'] = getAmplitude(bge.logic.micStream)
	#own['pitch'] = getPitch(bge.logic.micStream)
	
	backgroundNoise = -11
	velocityFactor = 1.0/25
	
	centerPoint = [0.0, 0.0, 0.0]
	if own['amplitude'] < backgroundNoise:
	    own['amplitude'] = backgroundNoise
	forwardVelocity = -backgroundNoise + own['amplitude']
	impulse = [0.0, (forwardVelocity * velocityFactor), 0.0]
	 
	own.applyImpulse(centerPoint, impulse)