diff --git a/src/pipecat/services/cartesia.py b/src/pipecat/services/cartesia.py index d1aa8b762..c3b6b905b 100644 --- a/src/pipecat/services/cartesia.py +++ b/src/pipecat/services/cartesia.py @@ -8,7 +8,7 @@ from cartesia import AsyncCartesia from typing import AsyncGenerator -from pipecat.frames.frames import AudioRawFrame, Frame +from pipecat.frames.frames import AudioRawFrame, CancelFrame, EndFrame, Frame, StartFrame from pipecat.services.ai_services import TTSService from loguru import logger @@ -28,22 +28,33 @@ class CartesiaTTSService(TTSService): super().__init__(**kwargs) self._api_key = api_key + self._voice_id = voice_id self._model_id = model_id self._output_format = { "container": "raw", "encoding": encoding, "sample_rate": sample_rate, } - - try: - self._client = AsyncCartesia(api_key=self._api_key) - self._voice = self._client.voices.get(id=voice_id) - except Exception as e: - logger.exception(f"{self} initialization error: {e}") + self._client = None def can_generate_metrics(self) -> bool: return True + async def start(self, frame: StartFrame): + try: + self._client = AsyncCartesia(api_key=self._api_key) + self._voice = self._client.voices.get(id=self._voice_id) + except Exception as e: + logger.exception(f"{self} initialization error: {e}") + + async def stop(self, frame: EndFrame): + if self._client: + await self._client.close() + + async def cancel(self, frame: CancelFrame): + if self._client: + await self._client.close() + async def run_tts(self, text: str) -> AsyncGenerator[Frame, None]: logger.debug(f"Generating TTS: [{text}]")