如何在python中获取定时输入?
How to get timed input in python?
我正在从事一个项目,我想将语音转换为文本。所以我为此使用 SpeechRecogniser。
语音识别器在检测到暂停后停止运行,但我不希望这种情况发生。我希望用户按 'q' 或 'Q' 停止语音转文本。
这是我试过的,
import speech_recognition as sr
import threading
r = sr.Recognizer()
def disp(text):
print(text)
with sr.Microphone() as source:
transcript = open('transcript.txt', 'w')
print('Start speaking')
while(True):
audio = r.listen(source)
try:
text = r.recognize_google(audio)
transcript.writelines(text)
except:
print('Inaudible. Try again.')
timer = threading.Timer(2.0, disp(text))
timer.start()
q = input()
try:
if q == 'q' or q == 'Q':
print('Ending transcript')
timer.cancel()
break
except NoneType:
continue
如果用户在他们停止说话后的 2 秒内选择退出,那么我希望它停止该过程。
我遇到的错误,
Start speaking
hello this is path
Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner
self.run()
File "/usr/lib/python3.6/threading.py", line 1182, in run
self.function(*self.args, **self.kwargs)
TypeError: 'NoneType' object is not callable
q
Ending transcript
提前致谢。
您的错误是如何将函数 dist 传递给 threading.Timer:
计时器 class 接受一个可调用函数,然后您发送 None(disp() 的结果)。
试试这个:
timer = threading.Timer(2.0, disp, args=(text,))
我正在从事一个项目,我想将语音转换为文本。所以我为此使用 SpeechRecogniser。
语音识别器在检测到暂停后停止运行,但我不希望这种情况发生。我希望用户按 'q' 或 'Q' 停止语音转文本。
这是我试过的,
import speech_recognition as sr
import threading
r = sr.Recognizer()
def disp(text):
print(text)
with sr.Microphone() as source:
transcript = open('transcript.txt', 'w')
print('Start speaking')
while(True):
audio = r.listen(source)
try:
text = r.recognize_google(audio)
transcript.writelines(text)
except:
print('Inaudible. Try again.')
timer = threading.Timer(2.0, disp(text))
timer.start()
q = input()
try:
if q == 'q' or q == 'Q':
print('Ending transcript')
timer.cancel()
break
except NoneType:
continue
如果用户在他们停止说话后的 2 秒内选择退出,那么我希望它停止该过程。
我遇到的错误,
Start speaking
hello this is path
Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner
self.run()
File "/usr/lib/python3.6/threading.py", line 1182, in run
self.function(*self.args, **self.kwargs)
TypeError: 'NoneType' object is not callable
q
Ending transcript
提前致谢。
您的错误是如何将函数 dist 传递给 threading.Timer: 计时器 class 接受一个可调用函数,然后您发送 None(disp() 的结果)。
试试这个:
timer = threading.Timer(2.0, disp, args=(text,))