Skip to content

Instantly share code, notes, and snippets.

@bancek
Created January 13, 2016 07:23
Show Gist options
  • Save bancek/bc4c633eadfee0d93543 to your computer and use it in GitHub Desktop.
Save bancek/bc4c633eadfee0d93543 to your computer and use it in GitHub Desktop.
Convert audio to mp3 and cut silence at the end
import os
import shutil
from glob import glob
import subprocess
output_path = 'mp3'
mp3_quality = '320k'
if os.path.exists(output_path):
shutil.rmtree(output_path)
os.makedirs(output_path)
input_files = list(glob('*.wav')) + list(glob('*.wma'))
for i, f in enumerate(input_files):
print f, i + 1, len(input_files)
last_silence_start = None
for line in subprocess.check_output('ffmpeg -i "%s" -af silencedetect=n=-20dB:d=1 -f null -' % f, shell=True, stderr=subprocess.STDOUT).splitlines():
if ' silence_start: ' in line:
last_silence_start = line.split(' silence_start: ')[1]
mp3_path = os.path.join(output_path, '.'.join(f.split('.')[:-1]) + '.mp3')
try:
if last_silence_start is None:
print 'No silence found'
subprocess.check_output('ffmpeg -i "%s" -b:a %s "%s"' % (f, mp3_quality, mp3_path), shell=True, stderr=subprocess.STDOUT)
else:
print 'Found silence after %s' % last_silence_start
subprocess.check_output('ffmpeg -i "%s" -t %s -b:a %s "%s"' % (f, last_silence_start, mp3_quality, mp3_path), shell=True, stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
print e.output
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment