#1secCounter.py import pyaudio import numpy as np import matplotlib.pyplot as plt import cv2 m = 1 threshold = input('Threshold?') with open('cps_data.csv', mode='w') as fc: fc.write('Time(sec)' + ',' + 'CPS' + '\n') cps_data = [] def streamandcount(): global m, threshold #stream CHUNK = 1024 FORMAT = pyaudio.paInt16 CHANNELS = 2 RATE = 44100 RECORD_SECONDS = 1 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 cps = pulse print('CPS = ' + str(int(cps))) cps_data.append(cps) with open('cps_data.csv', mode='a') as fc: fc.write(str(m) + ',' + str(cps) + '\n') fig = plt.figure(num = 1, figsize = (6, 7)) plt.subplot(211) plt.plot(data_l[200:1200]) plt.ylim(-250, 1000) plt.xlabel('t (msec/44)') plt.ylabel('PulseHeight') plt.subplot(212) plt.plot(cps_data) plt.xlim(0, 600) plt.ylim(0, 1000) plt.xlabel('t (sec)') plt.ylabel('CPS') plt.pause(0.3) plt.clf() while True: streamandcount() m = m + 1 if cv2.waitKey(0) & 0xFF == ord('q'): break