无法执行.mp3文件

时间:2017-07-23 00:37:04

标签: python python-2.7

我试图为Python创建一个基本上每五秒播放一次声音的脚本。

我的代码:

import time
import os

while True:
    path = '/Users/ColShell/Desktop/beep-08b.mp3'
    path.rstrip('/')
    os.system(path)
    time.sleep(5)

执行时出现此错误:

sh: /Users/ColShell/Desktop/beep-08b.mp3: cannot execute binary file

任何人都可以帮忙解释一下原因吗?

1 个答案:

答案 0 :(得分:2)

您正在尝试执行MP3文件,因此当然会抛出该错误 - 尝试在终端中粘贴/Users/ColShell/Desktop/beep-08b.mp3,看看会发生什么。

您是否尝试在默认系统播放器中播放该文件?这将取决于您的操作系统 - 我会根据您的路径假设MacOS X,因此您可以使用open来调用MP3文件的默认应用程序:

import subprocess

subprocess.call(["open", "/Users/ColShell/Desktop/beep-08b.mp3"])

但是,最好使用专为在后台播放声音而设计的应用程序,OSX为此afplay,所以:

import subprocess

subprocess.call(["afplay", "/Users/ColShell/Desktop/beep-08b.mp3"])

但如果您想直接在Python中播放声音,那么有几个选项 - 我个人认为function是最优雅的方法之一,所以安装它然后您可以轻松地使用它:

import playsound

playsound.playsound("/Users/ColShell/Desktop/beep-08b.mp3")

作为奖励 - 它(大部分)是跨平台的。