我想将一个应包含60s原始音频的numpy数组转换为.wav和.mp3文件。使用ffmpeg(版本3.4.6)时,我尝试将数组转换为所需的格式。为了进行比较,我还使用了模块化声音文件。由soundfile创建的.wav文件只有预期的60s长度。ffmpeg创建的.wav文件短一些,而.mp3-文件为ca。长32秒。
我希望所有出口的长度都相同。我做错了什么?
这是一个示例代码:
import subprocess as sp
import numpy as np
import soundfile as sf
def data2audiofile(filename,data):
out_cmds = ['ffmpeg',
'-f', 'f64le', # input 64bit float little endian
'-ar', '44100', # inpt samplerate 44100 Hz
'-ac','1', # input 1 channel (mono)
'-i', '-', # inputfile via pipe
'-y', # overwrite outputfile if it already exists
filename]
pipe = sp.Popen(out_cmds, stdin=sp.PIPE, stdout=sp.PIPE, stderr=sp.PIPE)
pipe.stdin.write(data)
data = (np.random.randint(low=-32000, high=32000, size=44100*60)/32678).astype('<f8')
data2audiofile('ffmpeg_mp3.mp3',data)
data2audiofile('ffmpeg_wav.wav',data)
sf.write('sf_wav.wav',data,44100)
此处结果文件以胆大程度显示:
您需要关闭pipe.stdin
并等待子流程结束。
关闭pipe.stdin
冲洗stdin
管道。
这里解释了这个主题:编写python子进程管道:
调用前关闭stdin(刷新并发送EOF)的键
wait
在下面添加以下代码行pipe.stdin.write(data)
:
pipe.stdin.close()
pipe.wait()
您也可以尝试在中设置较大的缓冲区大小sp.Popen
:
pipe = sp.Popen(out_cmds, stdin=sp.PIPE, stdout=sp.PIPE, stderr=sp.PIPE, bufsize=10**8)