#10secCounter.py import pyaudio import numpy as np import matplotlib.pyplot as plt import cv2 m = 1 threshold = input('Threshold?') with open('cpm_data.csv', mode='w') as fc: fc.write('Time(sec)' + ',' + 'CPM' + '\n') def streamandcount(): global m, threshold #stream CHUNK = 1024 FORMAT = pyaudio.paInt16 CHANNELS = 2 RATE = 44100 RECORD_SECONDS = 10 p = pyaudio.PyAudio() stream = p.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=True, frames_per_buffer=CHUNK) frames = [] for i in range(int(RATE * RECORD_SECONDS // CHUNK)): data_raw = stream.read(CHUNK) frames.append(data_raw) frames_int16 = np.array(frames) stream.stop_stream() stream.close() p.terminate() data = np.frombuffer(frames_int16, dtype='int16') #count pulse = 0 data_l = data[::2] onflag = False for k in range(len(data_l)): dat = data_l[int(k)] if int(dat) > int(threshold) and not onflag: pulse = pulse + 1 onflag = True if int(dat) <= int(threshold): onflag = False cpm = pulse / RECORD_SECONDS * 60 print('CPM = ' + str(int(cpm))) with open('cpm_data.csv', mode='a') as fc: fc.write(str(10 * m) + ',' + str(cpm) + '\n') while True: if cv2.waitKey(1) & 0xFF == ord('q'): break streamandcount() m = m + 1