-
Notifications
You must be signed in to change notification settings - Fork 1
/
speechtest.py
68 lines (60 loc) · 2.11 KB
/
speechtest.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
# NOTE: this requires PyAudio because it uses the Microphone class
from gtts import gTTS
import pygame
import speech_recognition as sr
import smtplib
# Import the email modules we'll need
from email.mime.text import MIMEText
import os
import time
import pyaudio
import wave
from winsound import *
# Open a plain text file for reading. For this example, assume that
# the text file contains only ASCII characters.
def speech_play_test(voice_output):
audio_file = "test.mp3"
tts = gTTS(text=voice_output, lang="en")
tts.save(audio_file)
pygame.mixer.init()
pygame.mixer.music.load(audio_file)
pygame.mixer.music.play()
while pygame.mixer.music.get_busy() == True:
continue
pygame.mixer.music.stop()
pygame.mixer.music.load("test2.mp3")
def audio_file_remove():
audio_file = "test.mp3"
os.remove(audio_file)
#Cannot remove audio file, have to remove it when entire application close
def speechrec():
playWav('ask.wav')
r = sr.Recognizer()
with sr.Microphone() as source: # use the default microphone as the audio source
audio = r.listen(source) # listen for the first phrase and extract it into audio data
try:
banana = r.recognize_google(audio, language = "en-us", show_all=False) # recognize speech using Google Speech Recognition
playWav('understood.wav')
return banana
except: # speech is unintelligible
errormess = "Could not understand audio, please try again"
speech_play_test(errormess)
def playWav(wavename):
chunk = 1024
f = wave.open(wavename, "rb")
p = pyaudio.PyAudio()
stream = p.open(format = p.get_format_from_width(f.getsampwidth()),
channels = f.getnchannels(),
rate = f.getframerate(),
output = True)
#read data
data = f.readframes(chunk)
#paly stream
while data != '':
stream.write(data)
data = f.readframes(chunk)
#stop stream
stream.stop_stream()
stream.close()
#close PyAudio
p.terminate()