树莓派调用百度语音合成短文本
时间: 2025-06-22 11:45:57 浏览: 12
### 调用百度语音合成API实现短文本转语音
要在树莓派上通过调用百度语音合成 API 实现短文本到语音的功能,可以按照以下方法操作:
#### 准备工作
首先需要注册并获取百度 AI 平台上的语音合成服务的相关密钥。登录百度开发者平台后,在控制台创建应用以获得 `API Key` 和 `Secret Key`[^1]。
#### 安装依赖库
在树莓派终端执行命令安装 Python 的 requests 库用于发送 HTTP 请求:
```bash
pip install requests
```
#### 编写Python脚本
下面是一个简单的 Python 脚本示例,展示如何利用百度语音合成接口完成文字转换成语音的任务:
```python
import os
import json
import base64
import requests
def get_token(api_key, secret_key):
url = 'https://aip.baidubce.com/oauth/2.0/token'
params = {
'grant_type': 'client_credentials',
'client_id': api_key,
'client_secret': secret_key
}
response = requests.get(url, params=params).json()
return response['access_token']
def text_to_speech(text, token, output_file='output.mp3'):
url = f'https://tsn.baidu.com/text2audio?tex={text}&lan=zh&cuid=baidu_speech_' \
f'demo&ctp=1&tok={token}'
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
result = requests.post(url=url, data=None, headers=headers)
if json.loads(result.content.decode('utf-8')).get('err_msg') is not None:
raise Exception(f'Error: {result.json()}')
with open(output_file, 'wb') as file:
file.write(result.content)
print("Audio saved to", output_file)
if __name__ == '__main__':
API_KEY = '<your_api_key>' # 替换为自己的API Key
SECRET_KEY = '<your_secret_key>' # 替换为自己的Secret Key
access_token = get_token(API_KEY, SECRET_KEY)
input_text = "你好,欢迎使用百度语音合成技术"
text_to_speech(input_text, access_token)
```
上述代码中包含了两个主要函数:一个是用来请求访问令牌 (`get_token`);另一个则是实际的文字转语音功能 (`text_to_speech`)。注意替换 `<your_api_key>` 和 `<your_secret_key>` 成为自己申请得到的真实值。
运行此程序之后将会生成名为 `output.mp3` 的文件保存至当前目录下,即为目标音频文件。
#### 播放音频文件
可以通过多种方式播放生成的 MP3 文件。如果是在图形界面环境下可以直接双击打开或者右键选择默认媒体播放器即可听到声音效果。对于无桌面环境下的纯命令行模式,则推荐采用如下工具之一来进行回放处理:
```bash
omxplayer output.mp3
aplay output.wav
mpg321 output.mp3
```
其中 omxplayer 是专门为 Raspberry Pi 设计的一个轻量级视频和音乐播放软件包,非常适合在这种小型设备上演示多媒体内容。
阅读全文
相关推荐


















