# -*- coding: utf-8 -*-
#
# Class: Audio
# - Convert Text to Speech using espeak
# - Convert Audio Input into Text using CMUSphinx and react on commands - offline
#
# ToDo:
# https://wiki.python.org/moin/PythonForArtificialIntelligence
# https://github.com/simpleai-team/simpleai
#
# Version: 0.1
# Creator: meigrafd
# Copyright (C) 2016 by meiraspi@gmail.com published under the MIT License
#
# Requires PyAudio.
import os
import speech_recognition
from espeak import espeak
from time import sleep, ctime
class AudioSpeakClass(object):
"""
Text to Speech
"""
def __init__(self, lang='de', speed=150):
self.lang = lang
self.speed = speed
def tts(self, text):
espeak.speed = self.speed
espeak.set_voice(self.lang)
espeak.synth(text)
class AudioCommandClass(object):
"""
Speech to Text and execute Commands
"""
def __init__(self, speak=None):
self.speak = speak
self.recognizer = speech_recognition.Recognizer()
with speech_recognition.Microphone() as source:
self.recognizer.adjust_for_ambient_noise(source)
self.mic = source
# start listening in the background (note that we don't have to do this inside a `with` statement)
self.stop_listening = self.recognizer.listen_in_background(self.mic, self.callback)
def stop(self):
self.stop_listening()
# this is called from the background thread
def callback(self, recognizer, audio):
# received audio data
try:
data = recognizer.recognize_sphinx(audio)
print("You said: " + data)
self.jarvis(data)
except speech_recognition.UnknownValueError:
print("Could not understand audio")
except speech_recognition.RequestError as e:
print("Recog Error; {0}".format(e))
def jarvis(self, data):
if "how are you" in data:
self.speak.tts("I am fine")
elif "what time is it" in data:
self.speak.tts(ctime())
def run():
audio_command = AudioCommandClass(speak=AudioSpeakClass())
try:
while True:
sleep(0.5)
except (KeyboardInterrupt, SystemExit):
pass
# EOF