Kode
pip install openai pygame
Kode
import openai
from pathlib import Path
import uuid
from datetime import datetime
import pygame
# Prompt the user for text to convert to speech
text_to_convert = input("Enter the text you want to convert to speech: ")
# Generate a unique filename using UUID and timestamp
unique_filename = f"{uuid.uuid4()}_{datetime.now().strftime('%Y-%m-%d_%H-%M-%S')}.mp3"
speech_file_path = Path.cwd() / unique_filename
# Initialize the OpenAI client
client = openai.OpenAI(api_key='sk-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
# The voice and model you want to use for audio generation
voice_to_use = "alloy" # Options: alloy, echo, fable, onyx, nova, shimmer
model_to_use = "tts-1" # For standard quality and lower latency. Use "tts-1-hd" for higher quality
# Generating spoken audio from text
response = client.audio.speech.create(
model=model_to_use,
voice=voice_to_use,
input=text_to_convert
)
# Streaming the response content to an mp3 file
response.stream_to_file(str(speech_file_path))
print(f"Audio file saved as {speech_file_path}")
# Initialize pygame mixer
pygame.mixer.init()
# Load the MP3 file
pygame.mixer.music.load(str(speech_file_path))
# Play the audio
pygame.mixer.music.play()
# Wait for the playback to finish
while pygame.mixer.music.get_busy():
pygame.time.Clock().tick(10)
print("Playback finished.")
Bruker pygame her for å spille av mp3