import os
import glob
import pyttsx3
engine = pyttsx3.init()
file_pattern = '*.txt'
file_name_list = []
if '*' in file_pattern:
file_name_list.extend(glob.glob(file_pattern))
# speech rate
engine.setProperty('rate', 600)
rate = engine.getProperty('rate')
# speech volume
volume = engine.getProperty('volume')
engine.setProperty('volume',1.0)
# speech voice
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[1].id)
engine.runAndWait() # engine start
for target in file_name_list:
string_to_parse = ''
with open(target,'r',encoding='utf-8', errors='ignore') as text_file:
for i in text_file.readlines():
string_to_parse = string_to_parse + i
mp3_filename = target.replace('.txt','.mp3')
fullPath = os.path.join(os.getcwd(), mp3_filename)
engine.save_to_file(string_to_parse, fullPath)
engine.runAndWait()
This code can write a folder full of small files containing one string to mp3, but if I try to convert multiple books it hangs up for eternity. What can I do?
You are writing a single line you should exit the for loop with the complete sentence in the variable string_to_parse and then you can save it to a mp3
import os
import glob
import pyttsx3
engine = pyttsx3.init()
file_pattern = '*.txt'
file_name_list = []
if '*' in file_pattern:
file_name_list.extend(glob.glob(file_pattern))
# speech rate
engine.setProperty('rate', 600)
rate = engine.getProperty('rate')
# speech volume
volume = engine.getProperty('volume')
engine.setProperty('volume',1.0)
# speech voice
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[1].id)
engine.runAndWait() # engine start
for target in file_name_list:
string_to_parse = ''
with open(target,'r',encoding='utf-8', errors='ignore') as text_file:
for i in text_file.readlines():
string_to_parse = string_to_parse + i
mp3_filename = target.replace('.txt','.mp3')
fullPath = os.path.join(os.getcwd(), mp3_filename)
engine.save_to_file(string_to_parse, fullPath)
engine.runAndWait()