用Python让树莓派“说话”

2014-03-107141
AI 快速预览详细 收起
本文介绍了如何使用Python脚本让树莓派发出真人发音。首先需要安装mplayer,然后通过调用Google TTS API生成语音URL,最后使用mplayer播放该URL。整个过程只需要写几行代码,非常适合初学者和STEM教育项目。

在这篇短文中我将告诉大家如何利用一段Python脚本让你的树莓派“说话”,还是真人发音的哦。因此,如果你想在自己的项目中增加一些人声,那么请跟着我的教程一步一步来,只需要写几行Python代码就能办到了。

在这个小项目中,你需要有这么几样东西:

  • 一台树莓派(显然必须得有这个)
  • 安装好兼容树莓派的操作系统(安装系统可利用NOOBS工具,傻瓜式安装哦)
  • 一对耳机/扬声器
  • 写几分钟的代码

首先你得安装mplayer,在终端中输入

[mw_shl_code=applescript,true]# Rollcode.com

import sys, subprocess, urllib

def getSpeech(phrase):
    googleAPIurl = "http://translate.google.com/translate_tts?tl=en&"
    param = {'q': phrase}
    data = urllib.urlencode(param)
    googleAPIurl += data # Append the parameters
    return googleAPIurl

def raspberryTalk(text): # This will call mplayer and will play the sound
    subprocess.call(["mplayer",getSpeech(text)], shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

if __name__ == "__main__":
    raspberryTalk("Hello from Rollcode.com")[/mw_shl_code]

我们可以将上述代码保存到一个文件中,就命名为TalkingPi.py吧。现在只要输入:

[mw_shl_code=applescript,true]sudo python TalkingPi.py[/mw_shl_code]

创作许可协议

本项目采用 None(不开放任何权利,保留所有权利) 进行许可。

评论(0)
- 没有更多了 -