Skip to content

Instantly share code, notes, and snippets.

@tjoen
Created March 6, 2018 17:11
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tjoen/bd37bdb8795363e9940f959b2394c5e2 to your computer and use it in GitHub Desktop.
Save tjoen/bd37bdb8795363e9940f959b2394c5e2 to your computer and use it in GitHub Desktop.
Dutch Google stt and tts in python
#!/usr/bin/env python
#-*- coding: utf-8 -*-
from gtts import gTTS
import os
import speech_recognition as sr
import tempfile
import time
import pyaudio
import wave
txt = "test"
def speech( txt ):
tts = gTTS(text=txt, lang="nl")
testfile = "/tmp/temp.mp3"
tts.save(testfile)
os.system("mpg123 /tmp/temp.mp3")
os.system("rm %s" %(testfile))
def record():
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 22050
CHUNK = 1024
RECORD_SECONDS = 5
WAVE_OUTPUT_FILENAME = "file.wav"
audio = pyaudio.PyAudio()
# start Recording
stream = audio.open(format=FORMAT, channels=CHANNELS,
rate=RATE, input=True,
frames_per_buffer=CHUNK)
print "recording..."
frames = []
for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
data = stream.read(CHUNK)
frames.append(data)
print "finished recording"
# stop Recording
stream.stop_stream()
stream.close()
audio.terminate()
waveFile = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
waveFile.setnchannels(CHANNELS)
waveFile.setsampwidth(audio.get_sample_size(FORMAT))
waveFile.setframerate(RATE)
waveFile.writeframes(b''.join(frames))
waveFile.close()
r = sr.Recognizer()
with sr.WavFile(WAVE_OUTPUT_FILENAME) as source: # use "test.wav" as the audio source
audio = r.record(source) # extract audio data from the file
# 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)`
global txt
txt = r.recognize_google(audio, None, "nl_NL")
print("Google Speech Recognition thinks you said " +txt )
return txt
except sr.UnknownValueError:
print("Google Speech Recognition could not understand audio")
return("Ik begrijp niet wat je zegt")
except sr.RequestError as e:
print("Could not request results from Google Speech Recognition service; {0}".format(e))
return "Fout in de spraakherkenning service"
spreq = record()
spc = speech( txt)
spreq = record()
spc = speech( txt)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment