Skip to content

Instantly share code, notes, and snippets.

@starenka
Last active September 26, 2022 13:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save starenka/0d7b230c01b90d59c29ab949ffdabc83 to your computer and use it in GitHub Desktop.
Save starenka/0d7b230c01b90d59c29ab949ffdabc83 to your computer and use it in GitHub Desktop.
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(
cmd,
shell=shell,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True)
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'ffmpeg'
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'{codecs_opts}'
f'{clip_len}'
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