首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >管道SoX在替代?

管道SoX在替代?
EN

Stack Overflow用户
提问于 2012-10-21 15:43:48
回答 1查看 10.5K关注 0票数 4

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

这样做很好:

代码语言:javascript
复制
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()将完整的文件加载到内存中;这是缓慢的,可能导致管道的缓冲区溢出。存在一种解决办法:

代码语言:javascript
复制
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?编写一个扩展之外,还有其他替代方法吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-10-21 16:56:03

SoX的Python包装器已经存在:索克斯。也许最简单的解决方案是切换到使用它,而不是通过SoX调用外部subprocess命令行实用程序。

使用sox包(请参阅文档)实现您在示例中所需的功能,并应在LinuxmacOS on Python2.73.4E 211E 1123.5E 213(它也可能在Windows上工作,但由于无法访问Windows框而无法进行测试):

代码语言:javascript
复制
>>> 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 

注意:这个答案曾经提到不再维护的http://packages.python.org/pysox/包。谢谢@erik的提示。

票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12999361

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档