python - remove silence at the beginning and at the end of wave files with PyDub -


how can remove silence beginning , end of wave files pydub?

i guess should access segment segment , check whether it's silent or not (but i'm not able it) :/

e.g. have wave file silence @ beginning, end, or both (like below) , want remove silence @ beginning , @ end of file:

wave file silence

e.g. want import

sound = audiosegment.from_wav(inputfile) 

cycle every sample of sound check whether it's silent , mark last silent sample since when waves starts (marker1), last sample before wave ends (marker2) , can export new sound file 2 markers

newsound = sound[marker1:marker2]  newsound.export(outputfile, format="wav") 

i advise cycle in chunks of @ least 10 ms in order little more (less iterations) , because individual samples don't have "loudness".

sound vibration, @ minimum take 2 samples detect whether there sound, (but tell high frequency).

anyway… work:

from pydub import audiosegment  def detect_leading_silence(sound, silence_threshold=-50.0, chunk_size=10):     '''     sound pydub.audiosegment     silence_threshold in db     chunk_size in ms      iterate on chunks until find first 1 sound     '''     trim_ms = 0 # ms     while sound[trim_ms:trim_ms+chunk_size].dbfs < silence_threshold:         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] 

Popular posts from this blog