简体   繁体   中英

How to get voice input with microphone in Python

How do you get voice input with microphone? This is the code

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"

Using google speech recognition, source

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

There are type errors in your code

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

You could also use it as a 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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