Python 文字转语音免费
时间: 2023-07-10 20:43:22 浏览: 94
要在 Python 中进行文字转语音,你可以使用 Google Text-to-Speech API。Google Text-to-Speech API 允许你通过提供一个文本字符串来生成一个音频文件,该音频文件可以是 WAV 或 MP3 格式。
以下是一个简单的 Python 代码示例,演示如何使用 Google Text-to-Speech API 将文本转换为语音:
```python
from google.cloud import texttospeech
# Replace with your Google Cloud project ID
project_id = 'your-project-id'
# Create the Text-to-Speech client
client = texttospeech.TextToSpeechClient()
# Set the text input to be synthesized
synthesis_input = texttospeech.SynthesisInput(text='Hello, world!')
# Build the voice request
voice = texttospeech.VoiceSelectionParams(
language_code='en-US',
name='en-US-Wavenet-D'
)
# Select the type of audio file you want returned
audio_config = texttospeech.AudioConfig(
audio_encoding=texttospeech.AudioEncoding.MP3
)
# Perform the text-to-speech request
response = client.synthesize_speech(
input=synthesis_input,
voice=voice,
audio_config=audio_config
)
# Save the audio file
with open('output.mp3', 'wb') as out:
out.write(response.audio_content)
print('Audio content written to file "output.mp3"')
```
请注意,使用 Google Text-to-Speech API 需要你拥有一个 Google Cloud Platform 帐号,并且需要设置适当的身份验证和授权。Google 提供了一定的免费配额,但在超出免费配额后,你可能需要支付一定的费用。
阅读全文