(这是在运行 2014-09-09-wheezy-raspbian 的 Raspberry Pi B 上,已运行更新和升级,安装并测试了 mplayer,使用 Python 3 进行编码)
我只涉足 Linux 和 Pi,所以我向专家寻求指导。
首先让我说这是可行的:
#!/bin/bash
say() { local IFS=+;/usr/bin/mplayer -ao alsa -really-quiet -noconsolecontrols "http://translate.google.com/translate_tts?tl=en&q=$*"; }
# say() { local IFS=+;/usr/bin/mplayer -ao alsa -really-quiet -noconsolecontrols "http://translate.google.co.uk/translate_tts?tl=en&q=$*"; }
say $*
这个 bash 脚本的执行方式如下: sudo ./speech.sh 鲍勃是你叔叔
Pi 愉快地访问 Google,并通过 mplayer 播放 TTS。这让我知道我的叔叔是谁。
我的问题发生在 Python 中。
我的最终目标是让一个小的 python 3 脚本在启动时启动,并且经常说一些随机语句。它将被安装在陶瓷头骨内,以取悦附近的鬼魂和食尸鬼。
这是我的 python 。希望有人能告诉我我做错了什么?
import urllib, os, random, urllib.request, urllib.parse, shutil, subprocess
def getGoogleSpeechURL(phrase):
print (phrase)
googleURL = "http://translate.google.com/translate_tts?tl=en&"
parameters = {'q': phrase}
data = urllib.parse.urlencode(parameters)
googleURL = "%s%s" % (googleURL, data)
return googleURL
def random_line(afileName):
with open(afileName, "r") as afile:
line = next(afile)
for num, aline in enumerate(afile):
if random.randrange(num + 2): continue
line = aline
return line
def speakSpeechFromText(phrase):
print (phrase)
googleSpeechURL = getGoogleSpeechURL(phrase)
commandString = '/usr/bin/mplayer -ao alsa -really-quiet -noconsolecontrols ' + googleSpeechURL
print (commandString)
os.system(commandString)
filePath = "/home/pi/TalkingSkullPhrases.txt"
speakSpeechFromText (random_line(filePath))
我尝试过 os.system、subprocess、Popen...但没有任何效果。系统调用只是打印命令字符串,然后退出(代码是否在 mplayer 之前结束?如果是这样,如何让它等待?)。子进程和 Popen 都提示它找不到 mplayer(我已经尝试了完全限定的路径,但没有成功)。
所以 *Nix 和 Python 大师,请注意指出我是如何成为一个白痴以及如何解决它。 :-)
最佳答案
使用subprocess
时的一个常见错误是它需要在列表中提供参数,而不是单个字符串(除非您使用一些选项,例如shell=True
)。所以你的 mplayer 调用应该是:
subprocess.call(['mplayer', '-ao', 'alsa', '-really-quiet', '-noconsolecontrols', googleSpeechURL])
关于python - 在 Raspberry Pi 上使用 Python 3,如何调用 MPlayer 并传递 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26006387/