Make your own AudioBook with Python Text to Speech using Python

Let’s make our own AudioBook with python. We do simple text to speech using python. For that, we get a text from our pdf. Instead of reading the pdf why you can’t convert it in AudioBook. Let’s do this.

Installation

We use pyttsx3 python module. pyttsx3 is a text-to-speech conversion library in Python. Unlike alternative libraries, it works offline and is compatible with both Python 2 and 3. Full doc: https://pyttsx3.readthedocs.io/en/latest/

To install this write following command in your terminal

pip install pyttsx3

On Linux make sure espeak is installed.

To extract text from pdf we use PyPDF2 python module. To install this write following command in your terminal

pip install PyPDF2

Code

import pyttsx3
import PyPDF2
    
book = open("/home/arpit/Desktop/python_tutorial.pdf", "rb")
pdf_reader = PyPDF2.PdfFileReader(book)

# if pdf contains more then one pages
pages = pdf_reader.numPages
print("Total Pages: ", pages)


speaker = pyttsx3.init()  # initialization
speaker.setProperty("rate", 125)  # set speaking speed

for page_num in range(pages):
    print("Current page: ", page_num + 1)
    page = pdf_reader.getPage(page_num)  # getting each pages from pdf

    text = page.extractText()  # extracting text from current page
    # print(text)
    speaker.say(text)  # now extract text will passed here to listen
    speaker.runAndWait()

Hope you enjoyed it. Be connected with this coding blog to get an awesome python project.

You may also like,