简体   繁体   中英

Unable to play & convert .txt to mp3 using GTTS

I'm trying to read a.txt file using Google's text-to-speech API. But, when I try to run it, it gives an error that I can't quite fathom. So your help will be greatly appreciated!

My Python code:

#Import the required module for text   
from gtts import gTTS 

#required to play the converted file
import os

#The file you want to convert
with open('/Users/humma/Desktop/python_projects/flowers.txt', 'r') as myFile:
    fileRead = myFile.read()

#passing file and language to the engine
myObj = gTTS(text = fileRead, lang = 'en-US', slow = False)
myObj.save('flowers.mp3')
os.system("flowers.mp3")

The error I get:

File "c:/Users/humma/Desktop/python_projects/txt-to-speech/txt-to-spch.py", line 12, in <module>
    myObj.save('flowers.mp3')
  File "C:\ProgramData\Anaconda3\lib\site-packages\gtts\tts.py", line 312, in save
    self.write_to_fp(f)
  File "C:\ProgramData\Anaconda3\lib\site-packages\gtts\tts.py", line 294, in write_to_fp
    raise gTTSError(tts=self, response=r)
gtts.tts.gTTSError: 200 (OK) from TTS API. Probable cause: Unknown

Thank you in advance for your time:)

from gtts import gTTS
from io import BytesIO
from pygame import mixer
import time

def speak():
    mp3_fp = BytesIO()
    tts = gTTS('You need to read documetation properly', lang='en')
    tts.write_to_fp(mp3_fp)
    tts.save("Audio.mp3")
    return mp3_fp

mixer.init()
sound = speak()
sound.seek(0)
mixer.music.load(sound, "mp3")
mixer.music.play()

It was lang = 'en-US' that caused the error. It's simply: lang = 'en'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM