jay57
jay57

Reputation: 3

Creating multiple audio file form a single Txt file

I'm trying to create multiple mp3 files based on one existing txt file. the txt file is separated by paragraphs. i have figured out to use gTTS to convert the text to audio but i'm having trouble with splitting the txt file.

single txt file:

[Hello Jay
Hello Tom]

I want to have two different audio file. one that says "Hello Jay" and another that says "Hello Tom"

I'm really new to python and i only managed to convert the txt file into audio at this point.

from gtts import gTTS

with open("1_3.txt", encoding = "utf-8") as file:
    file = file.read()

speak = gTTS(file, lang= "en")
speak.save("1_3.mp3")

Only managed to create one audio file that says both "Hello Jay Hello Tom"

Upvotes: 0

Views: 499

Answers (1)

tripleee
tripleee

Reputation: 189936

You are reading the whole file in one go, and then running the synthesizer on the entire text. You want to loop over the lines, and create one MP3 file for each line.

from gtts import gTTS

with open("1_3.txt", encoding = "utf-8") as lines:
    for index, line in enumerate(lines, 1):
        speak = gTTS(line, lang= "en")
        speak.save("1_3_{0}.mp3".format(index))

The enumerate wrapper is used to increment a number for each line. We use that to create a unique name for each output file. So the first line ends up in 1_3_1.mp3, the second, in 1_3_2.mp3, and so forth.

Upvotes: 1

Related Questions