How can I convert a text file to mp3 file?
Asked Answered
P

4

8

Here is my Python code:

import pyttsx3

engine = pyttsx3.init(driverName='sapi5')
f = open("tanjil.txt", 'r')
theText = f.read()
f.close()
engine.say(theText)
engine.runAndWait()

I couldn't save the file to an audio file.

Photophore answered 26/12, 2018 at 17:21 Comment(0)
H
7
import pyttsx3
engine = pyttsx3.init("sapi5")
voices = engine.getProperty("voices")[0] 
engine.setProperty('voice', voices)
text = 'Your Text'
engine.save_to_file(text, 'name.mp3')
engine.runAndWait() # don't forget to use this line
Hyphen answered 10/3, 2021 at 16:43 Comment(1)
This does not answer the question. The question specifically wants to read in a text file.Hachmann
A
6

As of July 14 2019, I'm able to save to file with the pyttsx3 library (without using another library or internet connection).

It doesn't appear to be documented, but looking at the source code in github for the Engine class in "engine.py" (https://github.com/nateshmbhat/pyttsx3/blob/master/pyttsx3/engine.py), I was able to find a "save_to_file" function:

def save_to_file(self, text, filename, name=None):
    '''
    Adds an utterance to speak to the event queue.
    @param text: Text to sepak
    @type text: unicode
    @param filename: the name of file to save.
    @param name: Name to associate with this utterance. Included in
        notifications about this utterance.
    @type name: str
    '''
    self.proxy.save_to_file(text, filename, name)

I am able to use this like:

engine.save_to_file('the text I want to save as audio', path_to_save)

Not sure the format - it's some raw audio format (I guess it's maybe something like aiff) - but I can play it in an audio player.

If you install pydub: https://pypi.org/project/pydub/

then you can easily convert this to mp3, e.g.:

from pydub import AudioSegment
AudioSegment.from_file(path_to_save).export('converted.mp3', format="mp3")
Allix answered 15/7, 2019 at 13:26 Comment(2)
Looked promising, but didn't work for me on windows. I probably use a different driver/proxy?Contextual
Now supported on windows and MacOS github.com/nateshmbhat/pyttsx3/issues/7Unwinking
L
5

I've tried @Brian's solution but it didn't work for me.

I searched around a bit and I couldn't figure out how to save the speech to mp3 in pyttx3 but I found another solution without pyttx3.

It can take a .txt file and directly output a .wav file,

def txt_zu_wav(eingabe, ausgabe, text_aus_datei = True, geschwindigkeit = 2, Stimmenname = "Zira"):
    from comtypes.client import CreateObject
    engine = CreateObject("SAPI.SpVoice")

    engine.rate = geschwindigkeit # von -10 bis 10

    for stimme in engine.GetVoices():
        if stimme.GetDescription().find(Stimmenname) >= 0:
            engine.Voice = stimme
            break
    else:
        print("Fehler Stimme nicht gefunden -> Standard wird benutzt")

    if text_aus_datei:
        datei = open(eingabe, 'r')
        text = datei.read()
        datei.close()
    else:
        text = eingabe

    stream = CreateObject("SAPI.SpFileStream")
    from comtypes.gen import SpeechLib

    stream.Open(ausgabe, SpeechLib.SSFMCreateForWrite)
    engine.AudioOutputStream = stream
    engine.speak(text)

    stream.Close()

txt_zu_wav("test.txt", "test_1.wav")
txt_zu_wav("It also works with a string instead of a file path", "test_2.wav", False)

This was tested with Python 3.7.4 on Windows 10.

Lithophyte answered 16/11, 2019 at 22:25 Comment(4)
So you just found it on the internet? Could you edit the link where you've found it into your post?Nugent
Oh I didn't mean that I literally found this function on a website and just copy pasted it. I made this.Lithophyte
Kindly mention, this is only working for Windows but not Mac, as the library COMTypes is designed for Windows, not Linux #37162060Eachern
please use english var names so everyone can understand it.Sardine
D
1

Try the following code snippet to convert text to audio and save it as an mp3 file.

import pyttsx3
from pydub import AudioSegment

# read text content from a file
f = open("tanjil.txt", 'r')
theText = f.read()
f.close()

# create audio file
engine = pyttsx3.init('sapi5')
engine.save_to_file(theText, 'test.mp3') # raw audio file
engine.runAndWait()

AudioSegment.from_file('test.mp3').export('test.mp3', format="mp3") # audio file in mp3 format 

NB: pyttsx3 save_to_file() method creates a raw audio file and it won't be useful for other applications to use even if we are able to play it in the media player. pydub is a useful package to convert raw audio into a specific format.

Depositary answered 4/10, 2022 at 18:39 Comment(1)
This does not answer the question. The question specifically wants to read in a text file.Hachmann

© 2022 - 2024 — McMap. All rights reserved.