我想把一个包含60秒原始音频的numpy数组转换成.wav和.mp3文件。使用ffmpeg(版本3.4.6),我尝试将数组转换为所需的格式。为了进行比较,我还使用modul声音文件。 只有soundfile创建的.wav文件的预期长度精确到60秒。ffmpeg创建的.wav文件略短,.mp3文件长约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)
此处显示audacity中显示的结果文件:
您需要关闭
pipe.stdin
并等待子进程结束关闭
pipe.stdin
将刷新stdin
管道。此处对主题进行了说明:Writing to a python subprocess pipe:
在
pipe.stdin.write(data)
之后添加以下代码行:您还可以尝试在
sp.Popen
中设置较大的缓冲区大小:相关问题 更多 >
编程相关推荐