python - 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] 中。
谢谢
解决方案
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...
推荐阅读
- node.js - 使用来自 GET 的 CSRF 令牌并在 POST 中使用它 | 403 禁止 | AWS 拉姆达
- android - 稍后如何设置视频文件的起点
- javascript - Intl.NumberFormat 货币:$US 货币符号?
- java - Spark RDD 过滤器在 Spark 流式传输之后立即进行
- python - 将循环中的每个抓取的元素保存到 json 文件
- sql - 单列中的两个约束
- generics - 生命周期子类型和泛型:“生命周期参数不允许”错误
- elasticsearch - 如何在 Elasticsearch 中停止重新索引?
- php - PHP/MySQL - 创建一个多维数组
- groovy - 如何在groovy中动态附加逗号分隔值