Skip to content

Instantly share code, notes, and snippets.

@wett1988
Last active April 16, 2024 12:28
Show Gist options
  • Save wett1988/d76acf6782ae61f4e7b884b005cc6697 to your computer and use it in GitHub Desktop.
Save wett1988/d76acf6782ae61f4e7b884b005cc6697 to your computer and use it in GitHub Desktop.
Split media file with timeline.json by ffmpeg and python
import ffmpeg
import argparse
import os
from datetime import timedelta
import csv
def parse_timeline(timeline_path):
timeline = []
with open(timeline_path, mode='r') as file:
csvFile = csv.DictReader(file, delimiter=',')
for lines in csvFile:
timeline.append(lines)
return timeline
def get_duration(input):
metadata = ffmpeg.probe(input)
return "{:0>8}".format(str(timedelta(seconds=float(metadata['format']['duration'].split('.')[0]))))
parser = argparse.ArgumentParser("Split media file by timeline with ffmpeg")
parser.add_argument("-i", dest='input', help="Source file path", type=str, required=True)
parser.add_argument("-d", dest='destination', help="Output destination", type=str, required=True)
parser.add_argument("-t", dest='timeline', help="Timeline file path", type=str, default='./timeline.csv')
parser.add_argument("-s", dest='pos_from', help="Timeline file path", type=str, default='00:00:00')
args = parser.parse_args()
os.makedirs(args.destination, exist_ok=True)
album = os.path.basename(args.destination)
pos_from = args.pos_from
input_file = args.input
timeline = parse_timeline(args.timeline)
timeline.append({'timeline': get_duration(input_file), 'title': 'eof'})
def convert(pos_from, pos_to, item, i):
metadata_list = []
metadata_list.append(f"title={item['title']}")
title = item['title']
if 'artist' in item:
metadata_list.append(f"artist={item['artist']}")
title = f"{item['artist']} - {title}"
if 'album' in item:
metadata_list.append(f"album={item['album']}")
else:
metadata_list.append(f"album={album}")
metadata_dict = {f"metadata:g:{i}": e for i, e in enumerate(metadata_list)}
ffmpeg.input(
input_file,
ss=(pos_from),
to=(pos_to),
).output(f"./{album}/{i} {title}.mp3", **metadata_dict).run(overwrite_output=True)
for i in range(len(timeline) - 1):
pos_to = timeline[i+1]['timeline']
item = timeline[i]
convert(pos_from, pos_to, item, i+1)
pos_from = pos_to
timeline title artist album
00:01:00 Title Artist Album
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment