File size: 1,596 Bytes
a73ec05
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# tts.py
import os
import tempfile
import requests
from playsound import playsound

def text_to_speech_openai(text, language="en"):
    """
    Convert text to speech using a hypothetical OpenAI TTS API.
    Note: OpenAI Whisper is for speech recognition.
    Replace the endpoint and parameters with actual API details when available.
    """
    import openai
    api_key = os.getenv("api_key_oai")
    if not api_key:
        raise ValueError("API key for OpenAI TTS not found in environment variable 'api_key_oai'")
    openai.api_key = api_key

    try:
        # Hypothetical API call -- adjust the engine name and parameters as per actual API documentation.
        response = openai.Audio.synthesize(
            engine="tts",      # Hypothetical engine name for TTS
            text=text,
            language=language
        )
        audio_url = response["audio_url"]
    except Exception as e:
        raise RuntimeError(f"OpenAI TTS synthesis failed: {e}")

    # Download and play the audio
    audio_data = requests.get(audio_url).content
    with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as tmp_file:
        tmp_file.write(audio_data)
        tmp_file_path = tmp_file.name
    playsound(tmp_file_path)

def text_to_speech_gtts(text, language="en"):
    """
    Fallback text-to-speech using the gTTS library.
    """
    from gtts import gTTS
    tts = gTTS(text=text, lang=language)
    with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as tmp_file:
        tts.save(tmp_file.name)
        tmp_file_path = tmp_file.name
    playsound(tmp_file_path)