cps-api-tx / voice.py
Ali2206's picture
device token
bd7030e
raw
history blame contribute delete
906 Bytes
from typing import Optional
from fastapi import HTTPException
import logging
import io
from gtts import gTTS
# Configure logging
logger = logging.getLogger(__name__)
def text_to_speech(text: str, language: str = "en", slow: bool = False) -> bytes:
"""
Convert text to speech using gTTS (Google Text-to-Speech)
Args:
text (str): The text to convert to speech
language (str): Language code (default: "en")
slow (bool): Whether to speak slowly (default: False)
Returns:
bytes: MP3 audio data
"""
try:
tts = gTTS(text=text, lang=language, slow=slow)
mp3_fp = io.BytesIO()
tts.write_to_fp(mp3_fp)
mp3_fp.seek(0)
return mp3_fp.read()
except Exception as e:
logger.error(f"Error in text-to-speech conversion: {e}")
raise HTTPException(status_code=500, detail="Error generating speech")