Home > Enterprise >  Python text to voice with pyttsx3
Python text to voice with pyttsx3

Time:03-21

So i wanted to convert a text into a mp3 file using pyttsx3 i wanted to apply a voice for the file but I was getting this error:

Traceback (most recent call last):
  File "c:\Users\user\Desktop\Informatik\Praktik\Projekte\Python\productivity\wikipedia_webscraper\main.py", line 32, in <module>
    engine.setProperty("voice", voice[1].id)
TypeError: 'module' object is not subscriptable

my code is:

import wikipedia as wiki
import os
import pyttsx3
from pyttsx3 import voice
user = os.path.expanduser('~').split('\\')[2]
serch = input("What are you serching for?")
serch_term = str(serch)
wiki.set_lang("de")
p = wiki.page(f'{serch_term}')
title1 = p.title
URl1 = p.url
Sumarry = wiki.summary(f'{serch_term}')
Content = p.content
with open(f'C:\\Users\\{user}\\Desktop\\{serch_term}.txt', 'w', encoding='utf-8-sig', newline='\r\n') as file:
    file.write(f'The Title is: {title1}')
    file.write(f'The URL is: {URl1}')
    file.write("\n")
    file.write(f'The Summary is: {Sumarry}')
    file.write("\n")
    file.write(f'The Full Content is: {Content}')
    file.close()
try: 
    with open(f'C:\\Users\\{user}\\Desktop\\{serch_term}.txt', 'r', encoding='utf-8-sig', newline='\r\n') as file:
        print(" The txt File was created sucesfully")
        file.close()
except:
    print("Something went wrong")

my_text = f'Der Titel ist: {title1}. {Sumarry}. {Content}.'
engine = pyttsx3.init()
engine = pyttsx3.init("sapi5")
engine.setProperty("voice", voice[1].id)
engine.runAndWait()
engine.save_to_file(my_text, f"C:\\Users\\{user}\\Desktop\\{serch_term}.mp3")

is_true = os.path.exists(f'C:\\Users\\{user}\\Desktop\\{serch_term}.mp3')
if is_true == True:
    print('Audio Version was created sucesfully')
else:
   print("Something went Wrong")

Does someone know how to solve that? The txt file was created btw

CodePudding user response:

The documentation set the voice in this way:

voices = engine.getProperty('voices')       #getting details of current voice
#engine.setProperty('voice', voices[0].id)  #changing index, changes voices. o for male
engine.setProperty('voice', voices[1].id)   #changing index, changes voices. 1 for female

Reference: https://pypi.org/project/pyttsx3/

  • Related