Commit 81aaa8b8 authored by Steve Tjoa's avatar Steve Tjoa

real time spectrogram

parent c28bf1e6
""" """
PyAudio Example: Make a wire between input and output (i.e., record a musicinformationretrieval.com/realtime_spectrogram.py
few samples and play them back immediately).
This is the callback (non-blocking) version. PyAudio example: display a live spectrogram in the terminal.
For more examples using PyAudio:
https://github.com/mwickert/scikit-dsp-comm/blob/master/sk_dsp_comm/pyaudio_helper.py
""" """
import librosa
import numpy import numpy
import pyaudio import pyaudio
import time import time
WIDTH = 2
CHANNELS = 1 CHANNELS = 1
RATE = 44100 RATE = 44100
FRAMES_PER_BUFFER = 1000
N_FFT = 4096
SCREEN_WIDTH = 178
BIN_LO = N_FFT*librosa.note_to_hz('C2')/RATE
BIN_HI = N_FFT*librosa.note_to_hz('C7')/RATE
FREQ_BINS = numpy.geomspace(BIN_LO, BIN_HI, SCREEN_WIDTH).astype('int')
p = pyaudio.PyAudio() p = pyaudio.PyAudio()
def g(z): def generate_string_from_audio(audio_data):
if z: x_fft = numpy.fft.rfft(audio_data, n=N_FFT)
return '*' X = numpy.log10(1 + 0.1*abs(x_fft))
else:
return ' ' char_list = [' ']*SCREEN_WIDTH
for i in range(len(FREQ_BINS)):
b = FREQ_BINS[i]
if X[b] > 0.3:
char_list[i] = '*'
elif i % 30 == 29:
char_list[i] = '|'
return ''.join(char_list)
def callback(in_data, frame_count, time_info, status): def callback(in_data, frame_count, time_info, status):
audio_data = numpy.fromstring(in_data, dtype=numpy.float32) audio_data = numpy.fromstring(in_data, dtype=numpy.float32)
X = numpy.log(abs(numpy.fft.fft(audio_data))) print( generate_string_from_audio(audio_data) )
print( ''.join(g(z > 1.5) for z in X[:140]) )
return (in_data, pyaudio.paContinue) return (in_data, pyaudio.paContinue)
stream = p.open(format=pyaudio.paFloat32, stream = p.open(format=pyaudio.paFloat32,
...@@ -31,12 +47,13 @@ stream = p.open(format=pyaudio.paFloat32, ...@@ -31,12 +47,13 @@ stream = p.open(format=pyaudio.paFloat32,
rate=RATE, rate=RATE,
input=True, input=True,
output=True, output=True,
frames_per_buffer=FRAMES_PER_BUFFER,
stream_callback=callback) stream_callback=callback)
stream.start_stream() stream.start_stream()
while stream.is_active(): while stream.is_active():
time.sleep(0.2) time.sleep(0.100)
stream.stop_stream() stream.stop_stream()
stream.close() stream.close()
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment