My code:
import subprocess
import os
import platform
class Speaker:
"""
Speaker class for differentiating different speech properties.
"""
def setVoice(self, voice):
self.voice = voice
def setWPM(self, wpm):
self.wpm = wpm
def setPitch(self, pitch):
self.pitch = pitch
def setProperties(self, voice="en", wpm=120, pitch=80):
self.setVoice(voice)
self.setWPM(wpm)
self.setPitch(pitch)
def __init__(self, voice="en", wpm=120, pitch=80):
self.prevproc = None
self.setProperties(voice, wpm, pitch)
self.executable = os.path.dirname(os.path.abspath(__file__)) +
"/espeak.exe" if platform.system() == 'Windows'
else os.path.dirname(os.path.abspath(__file__)) + "/espeak"
def generateCommand(self, phrase):
cmd = [
self.executable,
"--path=.",
"-v", self.voice,
"-p", self.pitch,
"-s", self.wpm,
phrase
]
cmd = [str(x) for x in cmd]
return cmd
def say(self, phrase, wait4prev=False):
cmd=self.generateCommand(phrase)
if wait4prev:
try: self.prevproc.wait()
except AttributeError: pass
else:
try: self.prevproc.terminate()
except AttributeError: pass
self.prevproc = subprocess.Popen(cmd, executable=self.executable,
cwd=os.path.dirname(os.path.abspath(__file__)))
How can the above code be improved?
Find it on GitHub: https://github.com/sayak-brm/espeak4py
Usage:
import espeak4py
import time
print('Testing espeak4py\n')
mySpeaker = espeak4py.Speaker()
mySpeaker.say('Testing', wait4prev=True)
print('Testing wait4prev')
mySpeaker.say('Hello, World!')
time.sleep(1)
mySpeaker.say('Interrupted!')
time.sleep(3)
mySpeaker.say('Hello, World!')
time.sleep(1)
mySpeaker.say('Not Interrupted.', wait4prev=True)
time.sleep(3)
print('Testing pitch')
myHighPitchedSpeaker = espeak4py.Speaker(pitch=120)
myHighPitchedSpeaker.say('I am a demo of the say function')
time.sleep(4)
print('Testing wpm')
myFastSpeaker = espeak4py.Speaker(wpm=140)
myFastSpeaker.say('I am a demo of the say function')
time.sleep(4)
print('Testing voice')
mySpanishSpeaker = espeak4py.Speaker(voice='es')
mySpanishSpeaker.say('Hola. Como estas?')
print('Testing Completed.')