Member-only story

Create an Audio Book using Python

Python Coding
2 min readSep 17, 2024

--

pip install gTTS

from gtts import gTTS
import os

def create_audiobook(text_file, output_file):
with open(text_file, 'r', encoding='utf-8') as file:
text = file.read()
tts = gTTS(text=text, lang='en')
tts.save(output_file)
print(f"Audiobook saved as {output_file}")

text_file = "clcodingtxt.txt"
output_file = "audiobook.mp3"

create_audiobook(text_file, output_file)

os.system(f"start {output_file}")

#source code --> clcoding.com
Audiobook saved as audiobook.mp3

Explanation:

1. Function Definition:

def create_audiobook(text_file, output_file):
  • This defines a function create_audiobook which takes two parameters:
  • text_file: The path to the text file you want to convert into an audiobook.
  • output_file: The name of the resulting audio file (in MP3 format).

2. Opening the Text File:

with open(text_file, 'r', encoding='utf-8') as file:
text = file.read()
  • open(text_file, 'r', encoding='utf-8'): This opens the file in read mode ('r') with UTF-8 encoding to properly handle special characters.
  • file.read(): Reads the entire content of the file into…

--

--

Python Coding
Python Coding

Written by Python Coding

Learn python tips and tricks with code I Share your knowledge with us to help society. Python Quiz: https://www.clcoding.com/p/quiz-questions.html

No responses yet