-
Notifications
You must be signed in to change notification settings - Fork 3
/
text_to_audiofile_openai.py
65 lines (52 loc) · 1.84 KB
/
text_to_audiofile_openai.py
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import os
import shutil
from dotenv import load_dotenv
from openai import OpenAI
from pydub import AudioSegment
# Load environment variables from the .env file
load_dotenv()
# Initialize the OpenAI client with the API key
api_key = os.getenv("OPENAI_API_KEY")
client = OpenAI(api_key=api_key)
# Configurable chunk size
CHUNK_SIZE = 4096
# Function to split text into chunks
def split_text(text, chunk_size=CHUNK_SIZE):
chunks = []
for i in range(0, len(text), chunk_size):
chunks.append(text[i:i+chunk_size])
return chunks
# Example text for demonstration
text = """
This is an example text that we will make audio for.
"""
# Split the extracted text into chunks
chunks = split_text(text)
# Print the number of chunks
print(f"Total chunks: {len(chunks)}")
# Directory to store individual chunk audio files
chunk_audio_dir = "chunk_audio"
os.makedirs(chunk_audio_dir, exist_ok=True)
# Synthesize audio for each chunk and save them as individual files
for j, chunk in enumerate(chunks):
print(f"Synthesizing audio for chunk {j+1}/{len(chunks)}...")
chunk_audio_path = os.path.join(chunk_audio_dir, f"chunk_{j+1}.mp3")
response = client.audio.speech.create(
model="tts-1-hd",
voice="onyx",
input=chunk,
response_format="mp3"
)
response.stream_to_file(chunk_audio_path)
# Combine the audio files
combined_audio = AudioSegment.empty()
for j in range(len(chunks)):
chunk_audio_path = os.path.join(chunk_audio_dir, f"chunk_{j+1}.mp3")
audio_segment = AudioSegment.from_file(chunk_audio_path, format="mp3")
combined_audio += audio_segment
# Save the combined audio to an MP3 file
output_path = "combined_output_text_audio.mp3"
combined_audio.export(output_path, format="mp3")
print(f"{output_path} saved successfully.")
# Clean up the directory with chunk audio files
shutil.rmtree(chunk_audio_dir)