Skip to content

Commit

Permalink
#49 | Nenad Pantelic | Add text-to-speech scripts
Browse files Browse the repository at this point in the history
  • Loading branch information
NenadPantelic committed Oct 18, 2019
1 parent 8ca3506 commit bcea4a6
Show file tree
Hide file tree
Showing 3 changed files with 86 additions and 0 deletions.
60 changes: 60 additions & 0 deletions TextToSpeech/tts.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
# possible replacement pyttsx3
from gtts import gTTS
import os
from utils import *
# tts audio config
PATH_TO_AUDIO_DIR = r"audio/"
DEFAULT_AUDIO_FILE = PATH_TO_AUDIO_DIR + "temporary.mp3"


class Speaker:
def __init__(self, language="en-us"):
self._language = language
self._tts = gTTS(lang=self._language, text="dummy")

# public methods
def set_language(self, language):
"""
Sets operating speaking _language.
:param str language: _language code
:rtype: None
:return: void method
"""
assert (isinstance(language, str))
self._language = language
self._tts.lang = self._language

def get_language(self):
"""
Returns speaking _language.
:rtype:str
:return: speaking _language
"""
return self._language

def save_speech_and_play(self, text=""):
"""
Speak out the given text. Text must not be empty string.
:param str text: text to be spoken
:rtype: None
:return: void method
"""
assert (isinstance(text, str))
if text != '':
self._speak(text, str(get_current_timestamp()) + ".mp3")

# private methods
def _speak(self, text, file_name=DEFAULT_AUDIO_FILE):
"""
Speak out and play audio.
:param str text:
:param str file_name: audio file in which speech will be saved
:rtype: None
:return:void method
"""
assert (isinstance(text, str))
if file_name != DEFAULT_AUDIO_FILE:
file_name = PATH_TO_AUDIO_DIR + file_name
self._tts.text = text
self._tts.save(file_name)
play_audio(file_name)
5 changes: 5 additions & 0 deletions TextToSpeech/tts_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
from tts import Speaker

speaker = Speaker("en-us")
print(speaker._speak("Marry had a little lamb!"))
print(speaker.save_speech_and_play(text="Hello, world!"))
21 changes: 21 additions & 0 deletions TextToSpeech/utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import time
from playsound import playsound

def play_audio(file_name):
"""
Play audio file.
:param str file_name: name of file that will be played.
:rtype: None
:return: void method
"""
assert (isinstance(file_name, str))
playsound(file_name)


def get_current_timestamp():
"""
Returns current timestamp as str.
:rtype: str
:return: current timestamp (Return the current time in seconds since the Epoch)
"""
return time.time()

0 comments on commit bcea4a6

Please sign in to comment.