Skip to content

Instantly share code, notes, and snippets.

Last active September 26, 2022 13:21
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
def run_shell_cmd(cmd, shell=False, log_errors=True):
log.debug('Running cmd %s', cmd)
cmd = shlex.split(cmd) if not shell else cmd
process = subprocess.Popen(
stdout, stderr = process.communicate()
return_code = process.poll()
if return_code:
if log_errors:
log.error('Not 0 RC (%s, shell=%s) returned from %s', return_code, shell, cmd,
extra=dict(stdout=stdout, stderr=stderr))
return False, return_code, cmd, stdout, stderr
return True, return_code, cmd, stdout, stderr
def extract_audio_to_wav_ffmpeg(fpath, out_path, max_len_secs=None, sample_rate=16000, channels=1, codecs_opts=''):
''' extracts audio to given format (out_path.format) from audio/video '''
FMAP = dict(wav='pcm_s16le', mp3='libmp3lame', flac='flac')
_, ext = os.path.splitext(out_path)
fmt = ext[1:]
if fmt not in FMAP:
raise ValueError('Not supported format: %s' % fmt)
codecs_opts = ' ' + codecs_opts if codecs_opts else ''
clip_len = ' -t %d' % max_len_secs if max_len_secs else ''
ok, rc, cmd, stdout, stderr = run_shell_cmd(
f' -hide_banner'
f' -nostats'
f' -loglevel warning'
f' -y' # overwrite output file
f' -vn' # remove video
f' -i \'{fpath}\''
f' -acodec {FMAP[fmt]}'
f' -ac {channels}'
f' -ar {sample_rate}'
f' \'{out_path}\'')
if not ok:
log.error('Fail to extract audio, cmd: %s, rc: %s, stdout: %s, stderr: %s',
cmd, rc, stdout, stderr, extra={'stack': True})
raise AudioExtractionError(stderr)
return ok
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment