Search code examples
pythonpyqt4pysidewave

What kind of files can gTTS save?


I want to make WAVE files by using gTTS module.

I downloaded gTTS module from https://pypi.python.org/pypi/gTTS`

I could make some files by it and stream the sounds by clicking these files.

But I want to know what kind of files can gTTS save? Here is the sample code:

import tempfile

from gtts import gTTS
tts = gTTS(text='hello', lang='en', slow=True)


tts.save("hello.wav")
f = tempfile.TemporaryFile()
tts.write_to_fp(f)
f.close()

When I used the soundfile with my code, I couldn't make it.

from PySide import QtGui
from PySide import QtCore
import sys
import os

class HelloSpeaker(QtGui.QPushButton):
    def __init__(self,parent=None):
        super(HelloSpeaker,self).__init__(parent=None)
        self.setText("Stream")
        self.connect(self,QtCore.SIGNAL("clicked()"),self.play_sound)
    def play_sound(self):
        sound = QtGui.QSound(os.getcwd()+"hello.wav")
        sound.play(os.getcwd()+"hello.wav")

def main():
    try:
        QtGui.QApplication([])
    except Exception as e:
        print(28,e)

    hello = HelloSpeaker()
    hello.show()

    sys.exit(QtGui.QApplication.exec_())
if __name__ == "__main__":
    main()

Yes, I found out some QSound-questions in stack overflow.

QSound don't work because of some unknown reasons.

For example:

QSound::play("soundpath") call works but a QSound object doesn't Playing sound with Pyqt4 and QSound QT5 QSound does not play all wave files

Other persons are bothered.

But I don't ascribed to QSound and I doubt that gTTS can't make .wav files. because

import wave
wf = wave.open("hello.wav", "rb")

result:

wave.Error: file does not start with RIFF id

I heard this error shows this file is not a wave file.

So I wonder that gTTS don't make ".wav" files. (But I can play it by ITunes , other players.)

Can gTTS make "mp3" files only?

environment:

python 3.6.3 pyside1.2.4 

Solution

  • gTTS only saves the bytes directly without doing any conversion, and these bytes are encoded in mp3, you can verify it by checking the source code:

    ....
    with warnings.catch_warnings():
        warnings.filterwarnings("ignore", category=InsecureRequestWarning)
        r = requests.get(self.GOOGLE_TTS_URL,
                         params=payload,
                         headers=headers,
                         proxies=urllib.request.getproxies(),
                         verify=False)
    if self.debug:
        print("Headers: {}".format(r.request.headers))
        print("Request url: {}".format(r.request.url))
        print("Response: {}, Redirects: {}".format(r.status_code, r.history))
    r.raise_for_status()
    for chunk in r.iter_content(chunk_size=1024): # write the bytes directly
        fp.write(chunk)
    ...