如果你有google云账号,可以自行参考(https://codelabs.developers.google.com/codelabs/cloud-text-speech-python3)完成体验。如果你没有google云账号,也不想用信用卡注册一个,但是又想快速体验一下,请继续读下去。本文将提供一个免费的Key,帮助你几分钟就完成一次初体验。
先说重点,Key我放在这里了,如果你知道怎么用就读到这里吧。
准备工作
安装相关python package
$ pip install ipython google-cloud-texttospeech
下载的Key放到当前目录后,设一下相关环境变量
$ export GOOGLE_APPLICATION_CREDENTIALS="csdn-386300-8cfa8afd6dcd.json"
打开VPN
如果没有VPN,可以参考视频教程(https://download.csdn.net/download/yingjil/87766019),或者文字教程(https://blog.csdn.net/yingjil/article/details/130571588)
试运行
$ ipython
在ipython中运行如下代码,可能需要多敲几次回车,确保运行
from typing import Sequenceimport google.cloud.texttospeech as ttsdef unique_languages_from_voices(voices: Sequence[tts.Voice]):language_set = set()for voice in voices:for language_code in voice.language_codes:language_set.add(language_code)return language_setdef list_languages():client = tts.TextToSpeechClient()response = client.list_voices()languages = unique_languages_from_voices(response.voices)print(f" Languages: {len(languages)} ".center(60, "-"))for i, language in enumerate(sorted(languages)):print(f"{language:>10}", end="\n" if i % 5 == 4 else "")
运行效果如下图
如果没有VPN,下一条语句就会执行失败
list_languages()
正常执行效果如下
看看支持哪些中文发音
import google.cloud.texttospeech as ttsdef list_voices(language_code=None):client = tts.TextToSpeechClient()response = client.list_voices(language_code=language_code)voices = sorted(response.voices, key=lambda voice: voice.name)print(f" Voices: {len(voices)} ".center(60, "-"))for voice in voices:languages = ", ".join(voice.language_codes)name = voice.namegender = tts.SsmlVoiceGender(voice.ssml_gender).namerate = voice.natural_sample_rate_hertzprint(f"{languages:<8} | {name:<24} | {gender:<8} | {rate:,} Hz")
运行
list_voices("cmn")
结果
转一个中文句子
在ipython中运行
import google.cloud.texttospeech as ttsdef text_to_wav(voice_name: str, text: str):language_code = "-".join(voice_name.split("-")[:2])text_input = tts.SynthesisInput(text=text)voice_params = tts.VoiceSelectionParams(language_code=language_code, name=voice_name)audio_config = tts.AudioConfig(audio_encoding=tts.AudioEncoding.LINEAR16)client = tts.TextToSpeechClient()response = client.synthesize_speech(input=text_input,voice=voice_params,audio_config=audio_config,)filename = f"{voice_name}.wav"with open(filename, "wb") as out:out.write(response.audio_content)print(f'Generated speech saved to "{filename}"')
再运行
text_to_wav("cmn-CN-Standard-A", "北京欢迎你")
运行效果如下
完事,听一下效果吧
cmn-CN-Standard-A.wav