python 不翻墙也能用 gtts

pip install gtts
下载的包中默认调用地址是 https://translate.google.com/translate_tts
需要翻墙才能连接,那么国内用户要如何使用呢?
很简单。
from gtts import gTTS as ts
help(ts) 后发现这两个参数,GOOGLE_TTS_HEADERS 和 GOOGLE_TTS_URL。里面都是 translate.google.com,只要把 com 改成 cn 就可以直接用了。
代码如下,简单粗暴:

from gtts import gTTS as ts
ts.GOOGLE_TTS_HEADERS = {'Referer': 'http://translate.google.cn/',
 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36'}
ts.GOOGLE_TTS_URL = 'https://translate.google.cn/translate_tts'

ts(text='hello world', lang='en').save('hello-world.mp3')

发现新大陆。

猜你喜欢

转载自blog.csdn.net/lhzlhk/article/details/88552135