DEV Community


Discussion on: Convert any .pdf file 📚 into an audio 🔈 book with Python

kushagra0347 profile image

This code gets stuck after I add PDF. can anyone provide any solution to this?

from tkinter import *
import pygame
import PyPDF2
from gtts import gTTS
from tkinter import filedialog
from os.path import splitext

root = Tk();
root.title('PDF Audio Player')

Initialise Pygame Mixer


Add PDF Function

def addPDF():
PDF = filedialog.askopenfilename(title="Choose a PDF", filetypes=(("PDF Files", "*.PDF"), ))
PDF_dir = PDF

# Strip Out the Directory Info and .pdf extension
# So That Only the Title Shows Up
PDF = PDF.replace('C:/Users/kusha/Downloads/', '')
PDF = PDF.replace(".pdf", '')

audioBookBox.insert(END, PDF)
Enter fullscreen mode Exit fullscreen mode

def PDFtoAudio(PDF_dir):
file = open(PDF_dir, 'rb')
reader = PyPDF2.PdfFileReader(file)
totalPages = reader.numPages
string = ""

for i in range(0, totalPages):
page = reader.getPage(i)
text = page.extractText()
string += text

outName = splitext(PDF_dir)[0] + '.mp3'
audioFile = gTTS(text=string, lang='en') # store file in variable # save file to computer

Enter fullscreen mode Exit fullscreen mode

Play Selected PDF Function

def play():
audio = audioBookBox.get(ACTIVE)
audio = f'C:/Users/kusha/Downloads/{audio}.mp3'
Enter fullscreen mode Exit fullscreen mode

Create Playlist Box

audioBookBox = Listbox(root, bg="black", fg="red", width = 70, selectbackground="gray", selectforeground="black")

Define Player Control Button Images

backBtnImg = PhotoImage(file='Project Pics/back50.png')
forwardBtnImg = PhotoImage(file='Project Pics/forward50.png')
playBtnImg = PhotoImage(file='Project Pics/play50.png')
pauseBtnImg = PhotoImage(file='Project Pics/pause50.png')
stopBtnImg = PhotoImage(file='Project Pics/stop50.png')

Create Player Control Frame

controlsFrame = Frame(root)

Create Player Control Buttons

backBtn = Button(controlsFrame, image=backBtnImg, borderwidth=0)
forwardBtn = Button(controlsFrame, image=forwardBtnImg, borderwidth=0)
playBtn = Button(controlsFrame, image=playBtnImg, borderwidth=0, command=play)
pauseBtn = Button(controlsFrame, image=pauseBtnImg, borderwidth=0)
stopBtn = Button(controlsFrame, image=stopBtnImg, borderwidth=0)

backBtn.grid(row=0, column=0, padx=10)
forwardBtn.grid(row=0, column=1, padx=10)
playBtn.grid(row=0, column=2, padx=10)
pauseBtn.grid(row=0, column=3, padx=10)
stopBtn.grid(row=0, column=4, padx=10)

Create Menu

myMenu = Menu(root)

Add the converted audio file in the menu

addAudioMenu = Menu(myMenu)
myMenu.add_cascade(label="Add PDF", menu=addAudioMenu)
addAudioMenu.add_command(label="Add One PDF", command=addPDF)