audiobook_tools/chapters.py
2023-10-08 14:48:58 -04:00

72 lines
1.6 KiB
Python

import math
import glob
import subprocess
from mutagen.mp3 import MP3
class Chapters:
def __init__(self, title, artist):
self.title = title
self.artist = artist
self.file_names = sorted(glob.glob("*.mp3"))
self.FFMETADATAFILE = f""";FFMETADATA1
title={self.title}
artist={self.artist}
encoder=libfdk_aac
"""
self.file_list = ""
def generate_metadata(self):
start = 1
for f in self.file_names:
self.file_list += f"file '{f}'\n"
mp3 = MP3(f)
l = int(mp3.info.length * 1000)
title = f[:-4]
self.FFMETADATAFILE += f"""[CHAPTER]
TIMEBASE=1/1000
START={start}
END={start+l}
title={title}
"""
start = start+l
def convert(self):
commands = [
'ffmpeg',
'-f', 'concat',
'-safe', '0',
'-i', 'file_list.txt',
'-i', 'FFMETADATAFILE.txt',
'-map_metadata', '1',
'-c:a', 'libfdk_aac',
'-b:a', '128k',
'-f', 'mp4', f'{self.title}.m4b',
]
if subprocess.run(commands).returncode == 0:
print("FFmpeg Script Ran Successfully")
else:
print("There was an error running your FFmpeg script")
def main():
title = input("Title: ")
artist = input("Artist: ")
ch = Chapters(title=title, artist=artist)
ch.generate_metadata()
with open("FFMETADATAFILE.txt", "w") as f:
print(ch.FFMETADATAFILE, file=f)
with open("file_list.txt", "w") as f:
print(ch.file_list, file=f)
ch.convert()
if __name__ == "__main__":
main()