使用 Python 到 trim 并使用 sox 填充 wav 文件而无需每次保存 wav 文件

Use Python to trim and pad wav file using sox without saving wav file each time

我发现 trim 和填充 wav 文件的最佳方法是使用 sox。但是,不是每次都保存转换后的文件,而是如何为转换后的 wav 文件生成一个变量?即不要每次都将转换后的wav文件保存到硬盘中,而是使用Python.

内的一个变量

代码

import librosa
import sox

# get the sample rate
sample_rate = sox.file_info.sample_rate(input_file)
# create transformer
tfm = sox.Transformer()
# trim the audio between 0 and 0.25 seconds.
tfm.trim(0, 0.25)

xx = 'test.wav'
tfm.build(input_file, xx)  # create the output file

tfm.pad(0, 0.75)
tfm.build(input_file, xx)  # create the output file
duration2 = sox.file_info.duration(xx)

真诚感谢任何帮助和指导!

谢谢!

您可以完全省略使用 sox 并使用 librosa 返回的 numpy 数组。 librosa.util.fix_length 如果文件比所需长度短,可以方便地用零填充。

durationSeconds = 0.5
data, sr = librosa.load("test.wav", sr=None, mono=False)
trimmed = librosa.util.fix_length(data, int(sr * durationSeconds))

如果以后要保存填充的wav文件:

librosa.output.write_wav("padded.wav", trimmed, sr)