繁体   English   中英

Python中如何通过麦克风获取语音输入

[英]How to get voice input with microphone in Python

你如何通过麦克风获得语音输入? 这是代码

import speech_recognition as sr

r = sr.Recognizer
with sr.Microphone() as source:

r.adjust_for_ambient_noise(source, duration=1)

print ("Listening...)
audio = r.listen(source)

try:
    text = r.recognize_google(audio)
except:
    print ("sorry"

使用谷歌语音识别, 来源

import speech_recognition as sr
print(sr.__version__) # just to print the version not required
r = sr.Recognizer()
my_mic = sr.Microphone(device_index=1) #my device index is 1, you have to put your device index
with my_mic as source:
    print("Say now!!!!")
    r.adjust_for_ambient_noise(source) #reduce noise
    audio = r.listen(source) #take voice input from the microphone
print(r.recognize_google(audio)) #to print voice into text

您的代码中存在类型错误

Import speech_recognition as sr

r = sr.Recognizer() # here
with sr.Microphone() as source:

r.adjust_for_ambient_noise(source, duration=1)

print ("Listening...") # here
audio = r.listen(source)

try:
    text = r.recognize_google(audio)
except:
    print ("sorry") # here

您也可以将其用作 function

def takeCommand():
    r = sr.Recognizer()
    with sr.Microphone() as source:
        sr.Recognizer().adjust_for_ambient_noise(source, duration=1)
        print("Listening...")
        audio = r.listen(source)

        try:
            text = r.recognize_google(audio)

        except Exception as e:
            return "Sorry"
        return text

暂无
暂无

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

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