如何使用PyDub从wave文件的开头和结尾删除静音?
我想我应该逐段访问并检查它是否无声(但我无法做到):/
e.g。我在开头,结尾或两者都有一个静音的波形文件(如下所示),我想删除文件开头和结尾处的静音:
e.g。我想导入它
sound = AudioSegment.from_wav(inputfile)
为每个声音样本循环以检查它是否静音并标记自波开始后的最后一个静音样本(marker1), 然后到波结束前的最后一个样本(marker2),我可以从两个标记中导出新的声音文件
newsound = sound[marker1:marker2]
newsound.export(outputfile, format="wav")
答案 0 :(得分:17)
我建议你以至少10毫秒的块为单位循环,以便更快地完成(更少的迭代),并且因为单个样本实际上没有“响度”。
声音是振动,所以至少需要2个样本来检测是否有任何声音,(但这只会告诉你高频率)。
无论如何......这样的事情可以奏效:
from pydub import AudioSegment
def detect_leading_silence(sound, silence_threshold=-50.0, chunk_size=10):
'''
sound is a pydub.AudioSegment
silence_threshold in dB
chunk_size in ms
iterate over chunks until you find the first one with sound
'''
trim_ms = 0 # ms
assert chunk_size > 0 # to avoid infinite loop
while sound[trim_ms:trim_ms+chunk_size].dBFS < silence_threshold and trim_ms < len(sound):
trim_ms += chunk_size
return trim_ms
sound = AudioSegment.from_file("/path/to/file.wav", format="wav")
start_trim = detect_leading_silence(sound)
end_trim = detect_leading_silence(sound.reverse())
duration = len(sound)
trimmed_sound = sound[start_trim:duration-end_trim]
答案 1 :(得分:1)
您可以使用-
from pydub.silence import detect_nonsilent
def remove_sil(path_in, path_out, format="wav"):
sound = AudioSegment.from_file(path_in, format=format)
non_sil_times = detect_nonsilent(sound, min_silence_len=50, silence_thresh=sound.dBFS * 1.5)
if len(non_sil_times) > 0:
non_sil_times_concat = [non_sil_times[0]]
if len(non_sil_times) > 1:
for t in non_sil_times[1:]:
if t[0] - non_sil_times_concat[-1][-1] < 200:
non_sil_times_concat[-1][-1] = t[1]
else:
non_sil_times_concat.append(t)
non_sil_times = [t for t in non_sil_times_concat if t[1] - t[0] > 350]
sound[non_sil_times[0][0]: non_sil_times[-1][1]].export(path_out)