-
Notifications
You must be signed in to change notification settings - Fork 1
/
test1.py
70 lines (57 loc) · 2.35 KB
/
test1.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import random
import time
import speech_recognition as sr
from ibm_watson import SpeechToTextV1
def recognize_speech_from_mic(recognizer, microphone):
"""Transcribe speech from recorded from `microphone`.
Returns a dictionary with three keys:
"success": a boolean indicating whether or not the API request was
successful
"error": `None` if no error occured, otherwise a string containing
an error message if the API could not be reached or
speech was unrecognizable
"transcription": `None` if speech could not be transcribed,
otherwise a string containing the transcribed text
"""
# check that recognizer and microphone arguments are appropriate type
if not isinstance(recognizer, sr.Recognizer):
raise TypeError("`recognizer` must be `Recognizer` instance")
if not isinstance(microphone, sr.Microphone):
raise TypeError("`microphone` must be `Microphone` instance")
# url = 'https://stream.watsonplatform.net/speech-to-text/api'
# pwd = 'Rlj8ifTeuLS9XCooI3HPmP9wROs1PN6lSv2Uijg0a0tk'
# speech_to_text = SpeechToTextV1(
# iam_apikey = pwd,
# url = url
# )
# adjust the recognizer sensitivity to ambient noise and record audio
# from the microphone
with microphone as source:
recognizer.adjust_for_ambient_noise(source)
audio = recognizer.listen(source)
# set up the response object
response = {
"success": True,
"error": None,
"transcription": None
}
# try recognizing the speech in the recording
# if a RequestError or UnknownValueError exception is caught,
# update the response object accordingly
try:
response["transcription"] = recognizer.recognize_google(audio)
except sr.RequestError:
# API was unreachable or unresponsive
response["success"] = False
response["error"] = "API unavailable"
except sr.UnknownValueError:
# speech was unintelligible
print("couldnt understand :(")
response["error"] = "Unable to recognize speech"
return response
if __name__ == "__main__":
recognizer = sr.Recognizer()
microphone = sr.Microphone(device_index=1)
print('Listening now...')
trans = recognize_speech_from_mic(recognizer, microphone)
print(trans['transcription'])