首页 > 解决方案 > Python如何将语音识别单词保存到列表中?

问题描述

import speech_recognition as sr 
import logging


def speechfrommicrophone():
    r = sr.Recognizer()
    mic = sr.Microphone()
    res=[]
    with mic as source:
        r.adjust_for_ambient_noise(source)
        audio = r.listen(source)
##        except sr.UnknownValueError:
##            print("Sphinx could not understand audio")
##        except sr.RequestError as e:
##            print("Sphinx error; {0}".format(e))
    try:
        res=r.recognize_google(audio, language='en-US')
        #print(type(res))
        print('You said:',res)
    except sr.UnknownValueError:
        print("Does not received any voice there")

for i in range(10):
    print('Please say something...')  
    speechfrommicrophone()
    print('End.')
    

如何将每次语音识别保存到一个列表中。例如,如果我说“你好”,如果我想在打印 res 之前列出我所说的内容,我想将该 hello 保存到一个列表 res[i] 中。

谢谢

标签: pythonspeech-recognition

解决方案


import speech_recognition as sr
import logging

res = []


def speechfrommicrophone():
    global res
    r = sr.Recognizer()
    mic = sr.Microphone()
    with mic as source:
        r.adjust_for_ambient_noise(source)
        audio = r.listen(source)
##        except sr.UnknownValueError:
##            print("Sphinx could not understand audio")
##        except sr.RequestError as e:
##            print("Sphinx error; {0}".format(e))
    try:
        a=r.recognize_google(audio, language='en-US')
        #print(type(res))
        print('You said:',a)
        res.append(a)

    except sr.UnknownValueError:
        print("Does not received any voice there")

for i in range(10):
    print('Please say something...')
    speechfrommicrophone()
    print('End.')
    print("you said:",res)

试试这个代码。它将你的 10 个声音保存在 res=[] 列表中

output:
Please say something...
You said: hello
End.
you said: ['hello']
Please say something...
You said: world
End.
you said: ['hello', 'world']
Please say something...

推荐阅读