要解决“AWS Polly文本转可下载的音频PCM文件无法正常工作”的问题,你可以尝试以下代码示例:
import boto3
def text_to_speech(text, output_file):
# 创建AWS Polly客户端
polly_client = boto3.client('polly', region_name='us-west-2') # 根据你的区域选择适当的区域
# 设置音频格式和编码
audio_format = 'pcm'
audio_encoding = 'pcm'
# 调用AWS Polly的synthesize_speech方法将文本转换为音频
response = polly_client.synthesize_speech(Text=text, OutputFormat=audio_format, SampleRate='16000',
VoiceId='Joanna')
# 保存音频到文件
with open(output_file, 'wb') as file:
file.write(response['AudioStream'].read())
# 示例调用
text = '这是一段测试文本。'
output_file = 'output.pcm'
text_to_speech(text, output_file)
请确保你已正确配置了AWS的凭证(如access_key_id和secret_access_key),并且已安装了boto3库。此示例使用Joanna
声音和16000
采样率,你可以根据自己的需求进行更改。