Skip to content

Instantly share code, notes, and snippets.

@sleepless-se
Last active June 21, 2021 08:27
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 sleepless-se/20ceb88b90bf22cba294c343818ef28e to your computer and use it in GitHub Desktop.
Save sleepless-se/20ceb88b90bf22cba294c343818ef28e to your computer and use it in GitHub Desktop.
import ffmpeg
import os
import logging
logger = logging.getLogger(__name__)
class MediaConverter:
@staticmethod
def to_flac(input_file_path)->str:
''' media file convert to flac
Args
input_file_path :(str)
Return
flac_file_path:(str)
'''
output_format = '.flac'
if input_file_path.endswith(output_format):return input_file_path
logger.info(f'input_file: {input_file_path}')
# create output file path
file_path = input_file_path[:input_file_path.rfind('.')]
output_file_path = file_path + output_format
logger.info(f'output_file: {output_file_path}')
# if there is a file, delete file.
if os.path.exists(output_file_path):os.remove(output_file_path)
# convert media to flac.
stream = ffmpeg.input(input_file_path)
audio = stream.audio
stream = ffmpeg.output(audio, output_file_path)
try:
ffmpeg.run(stream,capture_stdout=True, capture_stderr=True)
return output_file_path
except ffmpeg.Error as e:
logger.error('stdout:', e.stdout.decode('utf8'))
logger.error('stderr:', e.stderr.decode('utf8'))
raise e
@sleepless-se
Copy link
Author

sleepless-se commented Jun 21, 2021

Any media file convert to FLAC by ffmpeg-python in python

If you want to change another format, replace .flac.

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