Skip to content

Instantly share code, notes, and snippets.

@zeffii
Forked from hyperconcerto/matplotlib_fft.py
Last active August 18, 2016 12:23
Show Gist options
  • Save zeffii/fbd460b986a5c0ae869e66d91a75e90b to your computer and use it in GitHub Desktop.
Save zeffii/fbd460b986a5c0ae869e66d91a75e90b to your computer and use it in GitHub Desktop.
Matplotlib realtime audio FFT
#!/usr/bin/env python
# encoding: utf-8
## Module infomation ###
# Python (3.4.4)
# numpy (1.10.2)
# PyAudio (0.2.9)
# matplotlib (1.5.1)
# All 32bit edition
########################
import bpy
import numpy as np
import pyaudio
class SpectrumAnalyzer:
FORMAT = pyaudio.paFloat32
CHANNELS = 1
RATE = 16000
CHUNK = 512
START = 0
N = 512
wave_x = 0
wave_y = 0
spec_x = 0
spec_y = 0
data = []
def __init__(self):
self.pa = pyaudio.PyAudio()
self.stream = self.pa.open(
format=self.FORMAT,
channels=self.CHANNELS,
rate=self.RATE,
input=True,
output=False,
frames_per_buffer=self.CHUNK
)
def do_dataframe(self):
self.data = self.audioinput()
self.fft()
return self.wave_x, self.wave_y, self.N, self.spec_x, self.spec_y, self.RATE
def end_updates(self):
self.pa.close(stream=self.stream)
def audioinput(self):
ret = self.stream.read(self.CHUNK)
ret = np.fromstring(ret, np.float32)
return ret
def fft(self):
self.wave_x = range(self.START, self.START + self.N)
self.wave_y = self.data[self.START:self.START + self.N]
self.spec_x = np.fft.fftfreq(self.N, d=1.0 / self.RATE)
y = np.fft.fft(self.data[self.START:self.START + self.N])
self.spec_y = [np.sqrt(c.real ** 2 + c.imag ** 2) for c in y]
wik = SpectrumAnalyzer()
class ModalTimerOperator(bpy.types.Operator):
"""Operator which runs its self from a timer"""
bl_idname = "wm.modal_timer_operator"
bl_label = "Modal Timer Operator"
_timer = None
def modal(self, context, event):
if event.type in {'RIGHTMOUSE', 'ESC'}:
wik.end_updates()
self.cancel(context)
return {'CANCELLED'}
if event.type == 'TIMER':
print(wik.do_dataframe())
return {'PASS_THROUGH'}
def execute(self, context):
wm = context.window_manager
self._timer = wm.event_timer_add(0.1, context.window)
wm.modal_handler_add(self)
return {'RUNNING_MODAL'}
def cancel(self, context):
wm = context.window_manager
wm.event_timer_remove(self._timer)
def register():
bpy.utils.register_class(ModalTimerOperator)
def unregister():
bpy.utils.unregister_class(ModalTimerOperator)
if __name__ == "__main__":
register()
# test call
bpy.ops.wm.modal_timer_operator()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment