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

2024-05-01 22:01:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我想把一个包含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中显示的结果文件:


Tags: 文件importnumpydataas数组sfmp3
1条回答
网友
1楼 · 发布于 2024-05-01 22:01:36

您需要关闭pipe.stdin并等待子进程结束

关闭pipe.stdin将刷新stdin管道。
此处对主题进行了说明:Writing to a python subprocess pipe

The key it to close stdin (flush and send EOF) before calling 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)

相关问题 更多 >