File size: 1,448 Bytes
a5f1a61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
48
from pathlib import Path
from openai import OpenAI

class GPTTTS:
    def __init__(self, client):
        self.client = client

    def generate_speech(self, text="No text", model="tts-1-hd", voice="alloy"):
        """
        Generate speech from text using OpenAI's text-to-speech API.

        :param text: The text to convert to speech. Defaults to "No text".
        :param model: The TTS model to use. Defaults to "tts-1-hd".
        :param voice: The voice to use. Defaults to "alloy".
        :return: Path to the generated speech file.
        """
        # Set default values if parameters are empty
        model = model if model else "tts-1-hd"
        voice = voice if voice else "alloy"

        # Create the speech file path
        speech_file_path = Path(__file__).parent / "speech.mp3"

        # Generate the speech
        response = self.client.audio.speech.create(
            model=model,
            voice=voice,
            input=text
        )

        # Save the speech to a file
        response.stream_to_file(speech_file_path)

        return speech_file_path

# Example usage
if __name__ == "__main__":
    client = OpenAI()  # Initialize the OpenAI client
    tts = GPTTTS(client)

    # Generate speech
    file_path = tts.generate_speech(
        text="Today is a wonderful day to build something people love!",
        model="tts-1-hd",
        voice="alloy"
    )
    print(f"Speech generated at: {file_path}")