Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import pyaudio
- import numpy as np
- from scipy import integrate
- from time import sleep
- import serial
- from scipy.signal import savgol_filter
- try:
- ser = serial.Serial('COM3', 115200)
- except:
- print("error")
- sleep(2)
- RATE = 44100
- CHUNK = 4096
- maxbass = 1
- maxMid = 1
- maxHigh = 1
- totalArea = 1
- maxarea = 1
- counter = 1
- p = pyaudio.PyAudio()
- for i in range(p.get_device_count()):
- print(p.get_device_info_by_index(i))
- deviceInput = int(input("Type the Index of the device you want to use: "))
- stream = p.open(format = pyaudio.paInt16, channels = 1, rate = RATE, input = True, frames_per_buffer=CHUNK, input_device_index = deviceInput)
- while True:
- #plt.clf()
- #plt.axis([0,2000,0,3000000])
- if counter == 50:
- maxbass *= 0.8
- maxMid *= 0.98
- maxHigh *= 0.7
- counter = 1
- data = np.fromstring(stream.read(CHUNK), dtype = np.int16)
- data = data * np.hanning(len(data)) # smooth the FFT by windowing data
- data = savgol_filter(data, window_length = 51, polyorder = 4)
- fft = abs(np.fft.fft(data).real)
- fft = fft[:int(len(fft)/2)]
- freq = np.fft.fftfreq(CHUNK, 1.0/RATE)
- freq = freq[:int(len(freq)/2)]
- fft = fft[0:3000]
- freq = freq[0:3000]
- areaLow = integrate.simps(fft[25:400], freq[25:400], even='avg')
- areaMid = integrate.simps(fft[400:700], freq[400:700], even='avg')
- areaHigh = integrate.simps(fft[700:3000], freq[700:3000], even='avg')
- bass = fft[25:400]
- peakBass = fft[np.where(bass==np.max(bass))[0][0]]
- areaBass = ((areaLow * 0.3) + (peakBass * 0.7))
- if areaHigh > 255094:
- if areaHigh > maxHigh:
- maxHigh = areaHigh
- else:
- areaHigh = 0.0001
- if areaMid > 61500:
- if areaMid > maxMid:
- maxMid = areaMid
- else:
- areaMid = 0.0001
- if areaBass > 280000:
- #areaMid *= 0.7
- #areaHigh *= 0.8
- if areaBass > maxbass:
- areaMid *= 0.9
- maxbass = areaBass
- else:
- areaBass = 0.00001
- var = 2
- bassPerc = var * 1.2 * 700 * (areaBass / maxbass)
- #bassPerc = 1.2 * 1024 * (areaBass / maxbass)
- midPerc = var* 0.8 * 1024 * (areaMid / maxMid)
- highPerc = var * 0.8 * 1024 * (areaHigh / maxHigh)
- bassPerc = str(int(bassPerc))
- midPerc = str(int(midPerc))
- highPerc = str(int(highPerc))
- highPerc = highPerc.zfill(4)
- bassPerc = bassPerc.zfill(4)
- midPerc = midPerc.zfill(4)
- output = bassPerc + midPerc + highPerc + "$"
- ser.write(output.encode())
- print(output)
- sleep(0.05)
RAW Paste Data