Skip to content

Instantly share code, notes, and snippets.

@alexdelorenzo
Last active March 23, 2021 23:22
Show Gist options
  • Save alexdelorenzo/91a6c441c18f3f757fed6ecf124aa252 to your computer and use it in GitHub Desktop.
Save alexdelorenzo/91a6c441c18f3f757fed6ecf124aa252 to your computer and use it in GitHub Desktop.
Convert a video file's audio so it's Chromecast compatible
#!/usr/bin/env python3
#
# License: AGPLv3
# Copyright 2021 Alex DeLorenzo
# Requires Python 3.10+ and ffmpeg
#
from typing import Final
from subprocess import run
from pathlib import Path
from sys import argv
from os import cpu_count
import logging
NEW_SUFFIX: Final[str] = '_castconvert'
MP3_QUALITY: Final[int] = 1 # MP3 V1
THREADS: Final[int] = cpu_count() or 1
CMD_FMT: Final[str] = (
f'ffmpeg -y -fflags +genpts'
f' -i "{{orig}}"'
f' -c:a libmp3lame -q:a {MP3_QUALITY}'
f' -c:v copy -threads {THREADS}'
f' "{{new}}"'
)
def convert_audio(vid: Path) -> Path:
if NEW_SUFFIX in str(vid):
logging.info(f"Already converted: {vid}")
return vid
vid = vid.absolute()
new_stem: str = vid.stem + NEW_SUFFIX
new_vid: Path = vid.with_stem(new_stem)
new_vid = new_vid.absolute()
if new_vid.exists():
logging.info(f"Already converted: {new_vid}")
return new_vid
cmd: str = CMD_FMT.format(
orig=vid,
new=new_vid
)
run(cmd, shell=True)
return new_vid
def main():
vids: list[str]
_, *vids = argv
for vid in vids:
path = Path(vid)
new_path = convert_audio(path)
print(new_path)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment