0

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()
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153

1 Answers1

0

I don't know if this works, but you can try something like this:-

import time

start_timer = True
flag = True
while True:
    
    # read pitch
    pitch = ...
    
    current_time = time.time()
    
    if pitch == 12000 and flag:
        start_timer = True
        flag = False
    
    if pitch!= 12000:
        flag = True
    
    if start_timer:
        start_time = time.time()
        start_timer = False
        
    if start_timer - current_time>5:
        break

Ritwick Jha
  • 340
  • 2
  • 10