I am using the PyAudio and aubio libraries to read the tone coming in from a tone generator (Motorola Code Synthesizer II) which is plugged in to my computer via an Audio Jack usb port.(7.1 Channel Sound). I have code that can successfully read the pitch of the tone that the Tone Generator is set too. I am using a frequency of 1200 Hz to test my code. My goal is to have my code recognize that if a 1200 Hz tone is played for 5 seconds, it should stop listening (stop the stream) but I cannot seem to get my code to recognize how long the tone has been playing for.
I'm new to python and appreciate any help. My tone generator isn't exact so I am attempting to get my code to make sure the tone being heard is within a small range around 1200 Hz for 5 seconds before the stream should be closed.
My code:
# Pitch Detection
# Needed libraries
import aubio
import numpy as num
import pyaudio
import timeit
# PyAudio object
p = pyaudio.PyAudio()
# Open stream
stream = p.open(format=pyaudio.paFloat32,
channels=1, rate=44100, input=True,
frames_per_buffer=1024)
# Aubio's pitch detection
pDetection = aubio.pitch("default", 2048,
2048//2, 44100)
# Set unit
pDetection.set_unit("Hz")
pDetection.set_silence(-40)
# Listen
while True:
data = stream.read(1024)
samples = num.fromstring(data,
dtype=aubio.float_type)
pitch = pDetection(samples)[0]
print(pitch)
if 1198.50 < pitch < 1202.50:
#print('1200 Hz Detected')
timeout = 5
timeout_start = timeit.timeit()
while timeit.timeit() < timeout_start + timeout:
print('Longtone')
print(pitch)
break
else:
print('1200 Hz not detected')
# if time()==stop:
print("*** Longtone complete")
stream.stop_stream()
stream.close()
p.terminate()