|
""" |
|
pytts voice service (offline) |
|
""" |
|
|
|
import os |
|
import sys |
|
import time |
|
|
|
import pyttsx3 |
|
|
|
from bridge.reply import Reply, ReplyType |
|
from common.log import logger |
|
from common.tmp_dir import TmpDir |
|
from voice.voice import Voice |
|
|
|
|
|
class PyttsVoice(Voice): |
|
engine = pyttsx3.init() |
|
|
|
def __init__(self): |
|
|
|
self.engine.setProperty("rate", 125) |
|
|
|
self.engine.setProperty("volume", 1.0) |
|
if sys.platform == "win32": |
|
for voice in self.engine.getProperty("voices"): |
|
if "Chinese" in voice.name: |
|
self.engine.setProperty("voice", voice.id) |
|
else: |
|
self.engine.setProperty("voice", "zh") |
|
|
|
|
|
self.engine.startLoop(useDriverLoop=False) |
|
|
|
def textToVoice(self, text): |
|
try: |
|
|
|
wavFileName = "reply-" + str(int(time.time())) + "-" + str(hash(text) & 0x7FFFFFFF) + ".wav" |
|
wavFile = TmpDir().path() + wavFileName |
|
logger.info("[Pytts] textToVoice text={} voice file name={}".format(text, wavFile)) |
|
|
|
self.engine.save_to_file(text, wavFile) |
|
|
|
if sys.platform == "win32": |
|
self.engine.runAndWait() |
|
else: |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
self.engine.iterate() |
|
while self.engine.isBusy() or wavFileName not in os.listdir(TmpDir().path()): |
|
time.sleep(0.1) |
|
|
|
reply = Reply(ReplyType.VOICE, wavFile) |
|
|
|
except Exception as e: |
|
reply = Reply(ReplyType.ERROR, str(e)) |
|
finally: |
|
return reply |
|
|