#Spectrum.py import pyaudio import numpy as np import matplotlib.pyplot as plt CHUNK = 1024 FORMAT = pyaudio.paInt16 CHANNELS = 2 RATE = 44100 RECORD_SECONDS = 60 p = pyaudio.PyAudio() stream = p.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=True, frames_per_buffer=CHUNK) print("* recording") frames = [] for i in range(int(RATE * RECORD_SECONDS // CHUNK)): data_raw = stream.read(CHUNK) frames.append(data_raw) frames_int16 = np.array(frames) print("* done recording") stream.stop_stream() stream.close() p.terminate() data = np.frombuffer(frames_int16, dtype='int16') data_l = data[::2] data_max = int(max(data_l)) nu = 0 nd = 0 spectrum = [1 for i in range(1001)] threshold = int(data_max / 10) peak = int(threshold) for k in range(len(data_l)): dat = data_l[int(k)] if int(dat) > int(threshold): nu = nu + 1 if nu == 1: nd = 0 if int(dat) > peak: peak = int(dat) if int(dat) <= int(threshold): nd = nd + 1 if nd == 1: peakch = int(peak / data_max * 1000) spectrum[peakch] = spectrum[peakch] + 1 peak = int(threshold) nu = 0 with open('spectrum_data.csv', mode='w') as fs: for m in range(1, 1001): spect = spectrum[int(m)] fs.write(str(m) + ',' + str(spect) + '\n') plt.subplot(211) plt.plot(data_l) plt.subplot(212) plt.plot(spectrum) plt.show()