EastSync-AI / third_party_tools /text_to_audio_file.py
StanSava's picture
add elevenlabs summary at the end (#15)
c398d3e
import os
import base64
from elevenlabs.client import ElevenLabs
def text_to_audio_file(text: str, path: str = "output.mp3") -> str | None:
"""
Generate audio and save as a file. Returns:
- (filepath) if ok
- (None) if failed
"""
if not text:
return None
api_key = os.getenv("ELEVEN_LABS_API_KEY")
if not api_key:
print("API KEY MISSING")
return None
try:
client = ElevenLabs(api_key=api_key)
audio_stream = client.text_to_speech.convert(
text=text,
voice_id="NOpBlnGInO9m6vDvFkFC",
model_id="eleven_multilingual_v2",
output_format="mp3_44100_128"
)
audio_bytes = b"".join(audio_stream)
# FOR TESTING LOCAL FILE:
# with open("output.mp3", "rb") as f:
# audio_bytes = f.read()
with open(path, "wb") as f:
f.write(audio_bytes)
print('path', path)
return path
except Exception as e:
print("Audio generation failed:", e)
return None