This repository has been archived by the owner on Oct 14, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
speech.py
executable file
·82 lines (73 loc) · 2.82 KB
/
speech.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
71
72
73
74
75
76
77
78
79
80
81
82
#!/usr/bin/env python3
# NOTE: this example requires PyAudio because it uses the Microphone class
import notify2
import dbus
import settings
import speech_recognition as sr
import subprocess
notify2.init('LTU Assistant')
text_only_mode = False
def speak(message, also_cmd=False):
'''Speak the given message using the text-to-speech backend.'''
if also_cmd or text_only_mode:
print(message)
try:
notification = notify2.Notification('LTU Assistant',
message,
'notification-message-im')
notification.show()
except dbus.exceptions.DBusException:
if not also_cmd:
print(message)
if not text_only_mode:
if settings.voice == 'female':
# Speak using a female voice
subprocess.call('espeak -v+f1 "' + message + '"', shell=True)
else:
# Default to male voice
subprocess.call('espeak "' + message + '"', shell=True)
def listen():
'''Gets a command from the user, either via the microphone or command line
if text-only mode was specified.'''
if text_only_mode:
ret = raw_input('\t> ')
return True, ret
else:
# obtain audio from the microphone
r = sr.Recognizer()
ret = ""
with sr.Microphone() as source:
r.adjust_for_ambient_noise(source)
print("Say something!")
# Timeout after 10 seconds, in case this doesn't work
audio = r.listen(source, 10)
# recognize speech using Google Speech Recognition
try:
# for testing purposes, we're just using the default API key
# to use another API key, use `r.recognize_google(audio, key="GOOGLE_SPEECH_RECOGNITION_API_KEY")`
# instead of `r.recognize_google(audio)`
print("Sending recorded speech to Google...")
sentence = r.recognize_google(audio)
print("Google Speech Recognition thinks you said '" + sentence + "'.")
return True, sentence
except sr.UnknownValueError:
ret = "Google Speech Recognition could not understand audio."
except sr.RequestError:
ret = "Could not request results from Google Speech Recognition."
return False, ret
def ask_question(question, also_cmd=False):
'''Ask the user a question and return the reply as a string.'''
speak(question, also_cmd)
num_tries = 3
for x in range(0, num_tries):
(success, sentence) = listen()
if success:
return sentence
else:
speak('I\'m sorry, could you repeat that?', also_cmd)
speak('I\'m sorry, I could not understand you.', also_cmd)
return ''
if __name__ == '__main__':
(success, error) = listen()
if not success:
print(error)