如何在Python中使用语音识别检测一个单词

2024-04-29 16:52:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道如何用Python检测语音,但这个问题更具体: 如果Python能够识别单词,我如何使Python只监听一个单词,然后返回True。

我知道,我可以让Python一直听,然后做类似的事情 伪码:

while True:
    if stt.listen() == "keyword":
        return True

我已经做过了,节目在听了几分钟后就挂了。所以我需要一种只听一个特定单词的方法。

挂断是什么意思?程序没有崩溃,但没有响应。它不再听我的声音,当我按STRG + C时,它什么也不做。

我在寻找这样的东西:

while True:
    if stt.waitFor("keyword"):
        return True

希望你能理解,最好的问候


Tags: 方法程序truereturnif语音单词事情
1条回答
网友
1楼 · 发布于 2024-04-29 16:52:33
import sys, os
from pocketsphinx.pocketsphinx import *
from sphinxbase.sphinxbase import *
import pyaudio

modeldir = "../../../model"
datadir = "../../../test/data"

# Create a decoder with certain model
config = Decoder.default_config()
config.set_string('-hmm', os.path.join(modeldir, 'en-us/en-us'))
config.set_string('-dict', os.path.join(modeldir, 'en-us/cmudict-en-us.dict'))
config.set_string('-keyphrase', 'forward')
config.set_float('-kws_threshold', 1e+20)


p = pyaudio.PyAudio()
stream = p.open(format=pyaudio.paInt16, channels=1, rate=16000, input=True, frames_per_buffer=1024)
stream.start_stream()

# Process audio chunk by chunk. On keyword detected perform action and restart search
decoder = Decoder(config)
decoder.start_utt()
while True:
    buf = stream.read(1024)
    if buf:
         decoder.process_raw(buf, False, False)
    else:
         break
    if decoder.hyp() != None:
        print ([(seg.word, seg.prob, seg.start_frame, seg.end_frame) for seg in decoder.seg()])
        print ("Detected keyword, restarting search")
        decoder.end_utt()
        decoder.start_utt()

有关详细信息,请参见http://cmusphinx.sourceforge.net

相关问题 更多 >