"""The box's voice: earcons, and speech, which a press of the button stops.""" import logging import wave from button import PRESSED EARCONS = ("open", "turn", "gotit", "huh", "bye", "look") class Speaker: """play(name) starts an earcon and returns its length; play_wav(wav, button) plays speech. aplay is a Command for aplay on the speaker; sounds is the directory of earcons (a Path). An earcon isn't waited for: it plays while the mics listen. """ def __init__(self, aplay, sounds): self.__aplay, self.__sounds = aplay, sounds self.__lengths = {} for name in EARCONS: with (sounds / f"{name}.wav").open("rb") as f, wave.open(f) as w: self.__lengths[name] = w.getnframes() / w.getframerate() async def play(self, name): await self.__aplay.start(str(self.__sounds / f"{name}.wav")) return self.__lengths[name] async def play_wav(self, wav, button): """Play it to the end, and return True; or stop at a press, and return False.""" proc = await self.__aplay.spawn(stdout=False, stderr=False) async def feed(): try: proc.stdin.write(wav) await proc.stdin.drain() proc.stdin.close() except (BrokenPipeError, ConnectionResetError): pass await proc.wait() if await button.race(feed()) is PRESSED: proc.terminate() await proc.wait() return False return True class Voice: """speak(text): the speech capability's (piper), or espeak-ng if that fails; a press stops it.""" def __init__(self, say, espeak, speaker, button): self.__say, self.__espeak, self.__speaker, self.__button = say, espeak, speaker, button async def speak(self, text): try: wav = await self.__say.run(stdin=text.encode()) except Exception as err: logging.info(f"say failed, so espeak: {err}") wav = await self.__espeak.run(text) logging.info(f"saying: {text}") return await self.__speaker.play_wav(wav, self.__button)