温馨提示:本文翻译自stackoverflow.com,查看原文请点击:其他 - Why is mp3/wav duration different when I convert a numpy array with ffmpeg into audiofile (python)?
ffmpeg mp3 python wav soundfile

其他 - 当我将带有ffmpeg的numpy数组转换为音频文件(python)时,mp3 / wav持续时间为何不同?

发布于 2020-04-13 12:33:43

我想将一个应包含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)

此处结果文件以胆大程度显示:

查看更多

提问者
Mips
被浏览
105
Rotem 2020-02-04 06:15

您需要关闭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)