[英]Use Python to trim and pad wav file using sox without saving wav file each time
I found that the best way to trim and pad wav
files is to use sox
.我发现修剪和填充wav
文件的最佳方法是使用sox
。 However, instead of saving the transformed file each time, how to go about just generating a variable for the transformed wav
file?但是,不是每次都保存转换后的文件,go 如何为转换后的wav
文件生成一个变量? That is, do not save the transformed wav
file to the harddrive each time, but instead use a variable within Python.即不要每次都将转换后的wav
文件保存到硬盘中,而是使用Python内的一个变量。
CODE代码
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)
Any help and guidance is sincerely appreciated!真诚地感谢任何帮助和指导!
Thanks!谢谢!
you can entirely omit using sox and work with the numpy array returned by librosa.您可以完全省略使用 sox 并使用 librosa 返回的 numpy 数组。 librosa.util.fix_length
conveniently pads with zeros if the file is shorter than the desired length.如果文件短于所需长度, 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))
if you later want to save the padded wav file:如果您稍后想要保存填充的 wav 文件:
librosa.output.write_wav("padded.wav", trimmed, sr)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.