Skip to content

Instantly share code, notes, and snippets.

@mzmmoazam
Created April 2, 2018 12:13
Show Gist options
  • Save mzmmoazam/39b8f6f5c3972f227f2a93ef887d2def to your computer and use it in GitHub Desktop.
Save mzmmoazam/39b8f6f5c3972f227f2a93ef887d2def to your computer and use it in GitHub Desktop.
This gist uses your computer as a personal translator; converts English audio to Turkish audio.
import speech_recognition as sr, pyttsx
from googletrans import Translator
# pyttsx engine config
speech_engine = pyttsx.init('sapi5') # see http://pyttsx.readthedocs.org/en/latest/engine.html#pyttsx.init
speech_engine.setProperty('rate', 150)
# translator object
translator = Translator()
def speak(text):
'''
speaks the text(english) provided to it.
:param text: text provided in english -- str
:return: speaks using the speaker -- audio output
'''
speech_engine.say(text)
speech_engine.runAndWait()
def listen():
'''
no arguments , records audio from the microphone and converts it to text.
:return: text as interpretted from the audio(input voice recieved)
'''
# obtain audio from the microphone
r = sr.Recognizer()
with sr.Microphone() as source:
print("Listening....say something...")
audio = r.listen(source)
print("... audio recorded ...")
# 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)`
# for English
resp = r.recognize_google(audio, language="en-US")
print("Google Speech Recognition thinks you said in English: - " + resp)
return resp
except sr.UnknownValueError:
print("Google Speech Recognition could not understand audio")
except sr.RequestError as e:
print("Could not request results from Google Speech Recognition service; {0}".format(e))
return None
def translate(text):
'''
to convert english text to turkish text
:param text: The english text that was listened by the listen() module
:return: Turkish text
'''
translation = translator.translate(text=text,src='en',dest='tr')
return translation.text
def main():
audio = listen()
resp = translate(text=audio)
# print(resp)
speak(resp)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment