Skip to content

Instantly share code, notes, and snippets.

@sotelo
Created January 17, 2017 05:08
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save sotelo/be57571a1d582d44f3896710b56bc60d to your computer and use it in GitHub Desktop.
Save sotelo/be57571a1d582d44f3896710b56bc60d to your computer and use it in GitHub Desktop.
Remove silences
# From https://stackoverflow.com/questions/29547218/
# remove-silence-at-the-beginning-and-at-the-end-of-wave-files-with-pydub
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
while sound[trim_ms:trim_ms+chunk_size].dBFS < silence_threshold:
trim_ms += chunk_size
return trim_ms
if __name__ == '__main__':
import sys
sound = AudioSegment.from_file(sys.argv[1], 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]
trimmed_sound.export(sys.argv[1], format="wav")
@rbell1988
Copy link

Thanks, I will need to adapt your code snippet. I am just trying to find the optimal value for the silence threshold... Previously I used online app but just for a few files

@Mystified131
Copy link

Worked great, brilliant, thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment