简体   繁体   English

如何让代码在一段时间后检测到某种音调后停止运行?

[英]How can I make the code stop running after it has detected a certain tone after a set period of time?

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).我正在使用 PyAudio 和 aubio 库来读取来自音调发生器(摩托罗拉代码合成器 II)的音调,该音调发生器通过音频插孔 USB 端口插入我的计算机。(7.1 声道声音)。 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.我正在使用 1200 Hz 的频率来测试我的代码。 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.我的目标是让我的代码识别如果 1200 Hz 音调播放 5 秒,它应该停止收听(停止流),但我似乎无法让我的代码识别音调已经播放了多长时间。

I'm new to python and appreciate any help.我是 python 新手,感谢任何帮助。 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.我的音调发生器不准确,因此我正在尝试获取我的代码,以确保在关闭流之前,听到的音调在 1200 Hz 左右的小范围内持续 5 秒。

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()

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM