Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1import logging
2from typing import Optional
3import pyttsx3
6class TextToSpeechService:
7 """The TextToSpeechService is responsible for speech synthesis."""
9 tts: pyttsx3.Engine
11 def __init__(self, voice_id: Optional[str] = None) -> None:
12 self.tts = pyttsx3.init()
14 voices = [voice.id for voice in self.tts.getProperty('voices')]
15 if not voices: 15 ↛ 16line 15 didn't jump to line 16, because the condition on line 15 was never true
16 logging.warning(
17 "No voices were found - you may be missing additional dependencies on your system before you will hear any voice output.")
18 return
20 logging.info("Found voices: {}.".format(", ".join(voices)))
22 if voice_id:
23 if voice_id in voices:
24 self.tts.setProperty('voice', voice_id)
25 logging.info(f"Using voice: {voice_id}.")
26 else:
27 logging.warning(
28 f"Using the default voice due to an unknown voice_id: {voice_id}.")
29 else:
30 logging.info(
31 "Using the default voice as no voice_id was provided.")
33 def say(self, text: str) -> None:
34 """Converts the text into speech and outputs the audio.
36 Args:
37 text (str): The text to say.
38 """
40 self.tts.say(text)
41 self.tts.runAndWait()