Python中的管道SoX-子流程替代方案?
我在应用程序中使用。应用程序使用它对音频文件应用各种操作,例如修剪 这很好:Python中的管道SoX-子流程替代方案?,python,audio,subprocess,sox,inter-process-communicat,Python,Audio,Subprocess,Sox,Inter Process Communicat,我在应用程序中使用。应用程序使用它对音频文件应用各种操作,例如修剪 这很好: 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=op
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命令行实用程序
以下内容通过使用sox
包(请参阅)实现了您在示例中想要的功能,并且应该可以在Linux和macOS上使用Python 2.7、3.4和3.5(它也可以在Windows上工作,但我无法进行测试,因为我无法访问Windows框):
注意:这个答案曾经提到不再维护的包。感谢@erik提供的提示。奇怪的是,2011年和2016年都有这个包。最后一个的github页面命名为!但最后一个不适用于Python 3::-(维护的包现在似乎适用于Python 3!版本为1.3.2。
>>> 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