'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"
Solution 1:[1]
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
Solution 2:[2]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | nemesis |
| Solution 2 |
