python - Python 中的管道 SoX - 子进程替代方案?

标签 python audio subprocess sox inter-process-communicat

我使用 SoX在应用程序中。该应用程序使用它对音频文件应用各种操作,例如修剪。

这很好用:

from subprocess import Popen, PIPE

kwargs = {'stdin': PIPE, 'stdout': PIPE, 'stderr': PIPE}

pipe = Popen(['sox','-t','mp3','-', 'test.mp3','trim','0','15'], **kwargs)
output, errors = pipe.communicate(input=open('test.mp3','rb').read())
if errors:
    raise RuntimeError(errors)

然而,这将导致大文件出现问题,因为 read() 将整个文件加载到内存中;这很慢并且可能导致管道缓冲区溢出。存在解决方法:

from subprocess import Popen, PIPE
import tempfile
import uuid
import shutil
import os

kwargs = {'stdin': PIPE, 'stdout': PIPE, 'stderr': PIPE}
tmp = os.path.join(tempfile.gettempdir(), uuid.uuid1().hex + '.mp3')

pipe = Popen(['sox','test.mp3', tmp,'trim','0','15'], **kwargs)
output, errors = pipe.communicate()

if errors:
    raise RuntimeError(errors)

shutil.copy2(tmp, 'test.mp3')
os.remove(tmp)

所以问题如下:除了为 Sox C API 编写 Python 扩展之外,是否还有其他替代方法?

最佳答案

SoX 的 Python 包装器已经存在:sox .也许最简单的解决方案是改用它,而不是通过 subprocess 调用外部 SoX 命令行实用程序。

以下使用 sox 包(请参阅 documentation )在您的示例中实现您想要的,并且应该适用于 Linuxma​​cOSPython 2.73.43.5 上(它可能也适用于 Windows,但我无法测试,因为我不可以访问 Windows 框):

>>> import sox
>>> transformer = sox.Transformer()  # create transformer 
>>> transformer.trim(0, 15)  # trim the audio between 0 and 15 seconds 
>>> transformer.build('test.mp3', 'out.mp3')  # create the output file 

注意:此答案用于提及不再维护的 pysox包裹。感谢@erik 的提示。

关于python - Python 中的管道 SoX - 子进程替代方案?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12999361/

相关文章:

Python:正则表达式提取html中任意两个标签之间的文本

python - 如何在 pandas 或 python 中分割特定范围的日期

javascript - MapReduce 上的 Riak 排序

javascript - Web Audio API - 合并两个音频缓冲区

jquery - 如何使用JQuery播放连续的歌曲?

python用脚本执行exe文件,输入用户名,密码等

python - Django Rest Framework - APIView 分页

android - 错误: Audio Priority Boost

python - 多个目录的错误处理

python - 以附加模式将子进程输出转储到文件中