Python文字轉語音(Text TO Speech)

text_file_to_speech.py

Yanwei Liu
3 min readSep 14, 2019

安裝

pip install gtts

文字檔案轉語音

# Import the Gtts module for text  
# to speech conversion
from gtts import gTTS

# import Os module to start the audio file
import os

fh = open("test.txt", "r")
myText = fh.read().replace("\n", " ")

# Language we want to use
language = 'en'

output = gTTS(text=myText, lang=language, slow=False)

output.save("output.mp3")
fh.close()

# Play the converted file
os.system("start output.mp3")

文字轉語音

# Import the Gtts module for text  
# to speech conversion
from gtts import gTTS

# import Os module to start the audio file
import os

mytext = 'Convert this Text to Speech in Python'

# Language we want to use
language = 'en'
myobj = gTTS(text=mytext, lang=language, slow=False)
myobj.save("output.mp3")

# Play the converted file
os.system("start output.mp3")

20191228更新

#英文
from gtts import gTTS
tts = gTTs("Hello world")
tts.save("hello.mp3")
#中文
from gtts import gTTS
tts = gTTs("說中文", lang="zh-tw")
tts.save("hello.mp3")
#日文
from gtts import gTTS
tts=gTTS(text='ありがとう', lang='ja')
tts.save("japanese_thank_you.mp3")
#寫成函式import time
from gtts import gTTS
from pygame import mixer
import tempfile
def speak(sentence, lang):
with tempfile.NamedTemporaryFile(delete=True) as fp:
tts=gTTS(text=sentence, lang=lang)
tts.save('{}.mp3'.format(fp.name))
mixer.init()
mixer.music.load('{}.mp3'.format(fp.name))
mixer.music.play(1)
speak('ありがとう', 'ja')
time.sleep(1)
speak('高雄發大財', 'zh-tw')
time.sleep(3)
speak('bonjour', 'fr')
time.sleep(1)
speak('Guten Tag', 'de')
time.sleep(1)
speak('Hello World!', 'en')
time.sleep(1)

--

--