Last active
July 17, 2022 14:29
-
-
Save 505e06b2/981825bd8e28581d88f58353baaf8571 to your computer and use it in GitHub Desktop.
Encode audio files as webm using the album art as the video track
This file contains hidden or 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
#!/usr/bin/env python3 | |
import sys, subprocess, shlex, json | |
from pathlib import Path | |
temp_folder = "/tmp" | |
album_art_filename = Path(temp_folder, "script_album_art.jpg") | |
try: | |
audio_path = Path(sys.argv[1].strip()) | |
if not audio_path.is_file(): | |
print(f"File at \"{audio_path}\" does not exist") | |
exit(1) | |
except IndexError: | |
print("Must pass the path of an audio file") | |
exit(1) | |
print(f"Extracting Album Art from audio file to \"{album_art_filename}\"") | |
try: | |
subprocess.check_call(shlex.split(f"ffmpeg -v quiet -y -i \"{audio_path}\" -an -c:v copy \"{album_art_filename}\"")) | |
except subprocess.CalledProcessError: | |
print(f"No Album Art found in \"{audio_path}\"") | |
exit(1) | |
print("Parsing metadata") | |
raw_ffprobe = subprocess.check_output(shlex.split(f"ffprobe -v quiet -print_format json -show_streams -show_format \"{audio_path}\"")) | |
parsed_metadata = json.loads(raw_ffprobe.decode("utf8")) | |
found_pieces = {"title": None, "artist": None} | |
if parsed_metadata["format"].get("tags"): #mp3 stores them here | |
tags = parsed_metadata["format"]["tags"] | |
found_pieces["title"] = tags.get("TITLE") or tags.get("title") | |
found_pieces["artist"] = tags.get("ARTIST") or tags.get("artist") | |
if not (found_pieces["title"] and found_pieces["artist"]): #search streams (opus/etc) | |
for i in range(len(parsed_metadata["streams"])): | |
stream = parsed_metadata["streams"][i] | |
if stream["codec_type"] == "audio" and stream.get("tags"): | |
tags = stream["tags"] | |
found_pieces["title"] = tags.get("TITLE") or tags.get("title") | |
found_pieces["artist"] = tags.get("ARTIST") or tags.get("artist") | |
metadata_stream = f"1:s:{i}" | |
break | |
if found_pieces["title"] and found_pieces["artist"]: | |
webm_path = f"{found_pieces['artist']} - {found_pieces['title']}.webm" | |
else: | |
webm_path = Path(audio_path).stem + ".webm" | |
print(f"Writing webm to \"{webm_path}\"") | |
subprocess.check_call(shlex.split(f"ffmpeg -v quiet -y -i \"{album_art_filename}\" -i \"{audio_path}\" -c:v libvpx-vp9 -c:a libopus -vf scale=360:360 -af silenceremove=start_periods=1:stop_periods=1:detection=peak -map_metadata 1 -threads 10 -row-mt 1 -tile-rows 2 \"{webm_path}\"")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment