Last active
January 16, 2019 10:39
-
-
Save MCOfficer/02003168ecd1111dd4204ee0f42cb194 to your computer and use it in GitHub Desktop.
[Python] Simple Script that Splits an audio file by it's metadata chapters using ffmpeg. Supports reading chapters from one file and splitting a different one. Useful for audio book conversion. No modules required, only ffmpeg/ffprobe binaries in your PATH
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from subprocess import check_output, call, DEVNULL | |
from json import loads | |
from os import makedirs | |
from os.path import join, exists, splitext | |
from string import ascii_letters, digits | |
# if your ffmpeg commands are different, change them here | |
FFMPEG = "ffmpeg" | |
FFPROBE = "ffprobe" | |
# stolen from https://gist.github.com/seanh/93666, thank you very much | |
def format_filename(s): | |
valid_chars = "-_.() %s%s" % (ascii_letters, digits) | |
filename = ''.join(c for c in s if c in valid_chars) | |
filename = filename.replace(' ','_') # I don't like spaces in filenames. | |
return filename | |
chapterfile = input("File to fetch chapters from: ") | |
inputfile = input("Input File (leave empty to use chapter-file): ") | |
if inputfile == "": | |
inputfile = chapterfile | |
outputfolder = input("Folder to write chapters to: ") | |
print("Checking " + chapterfile + " for chapters...") | |
chapterinfo = check_output(FFPROBE + " " + chapterfile + " -show_chapters -of json", shell=True, stderr=DEVNULL) | |
chapters = loads(chapterinfo)["chapters"] | |
chapterlen = str(len(chapters) + 1) | |
print("Found " + chapterlen + " chapters") | |
if not exists(outputfolder): | |
makedirs(outputfolder) | |
for chapter in chapters: | |
chapterid = str(chapter["id"] + 1) | |
try: | |
title = chapter["tags"]["title"] | |
except KeyError: | |
print("Chapter " + chapterid + " does not seem to have a title") | |
title = chapterid | |
print("Slicing chapter " + chapterid + " of " + chapterlen + "...") | |
outputfile = join(outputfolder, format_filename(title + splitext(inputfile)[1])) | |
start = str(int(float(chapter["start_time"]))) | |
duration = str(int(start) - int(float(chapter["start_time"]))) | |
call(FFMPEG + " -ss " + start + " -i " + inputfile + " -t " + duration + " -c copy " + outputfile, shell=True) | |
print("...Done") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment