From 97dbacad04e8e4a01efffe57276bcab2ffad6200 Mon Sep 17 00:00:00 2001 From: BennyThink Date: Sun, 13 Mar 2022 13:12:18 +0800 Subject: [PATCH] better direct audio --- ytdlbot/config.py | 2 +- ytdlbot/downloader.py | 27 ++++++++++++++++++++++++--- ytdlbot/tasks.py | 2 +- 3 files changed, 26 insertions(+), 5 deletions(-) diff --git a/ytdlbot/config.py b/ytdlbot/config.py index 5db5198..85c737f 100644 --- a/ytdlbot/config.py +++ b/ytdlbot/config.py @@ -51,7 +51,7 @@ MYSQL_HOST = os.getenv("MYSQL_HOST") MYSQL_USER = os.getenv("MYSQL_USER", "root") MYSQL_PASS = os.getenv("MYSQL_PASS", "root") -AUDIO_FORMAT = os.getenv("AUDIO_FORMAT", "m4a") +AUDIO_FORMAT = os.getenv("AUDIO_FORMAT") ARCHIVE_ID = os.getenv("ARCHIVE_ID") IPv6 = os.getenv("IPv6", False) diff --git a/ytdlbot/downloader.py b/ytdlbot/downloader.py index aeac189..e901ce4 100644 --- a/ytdlbot/downloader.py +++ b/ytdlbot/downloader.py @@ -257,11 +257,32 @@ def ytdl_download(url, tempdir, bm) -> dict: def convert_audio_format(resp: "dict", bm): + # 1. file is audio, default format + # 2. file is video, default format + # 3. non default format if resp["status"]: - # all_converted = [] - path: pathlib.PosixPath + path: "pathlib.Path" for path in resp["filepath"]: - if path.suffix != f".{AUDIO_FORMAT}": + streams = ffmpeg.probe(path)["streams"] + if (AUDIO_FORMAT is None and + len(streams) == 1 and + streams[0]["codec_type"] == "audio"): + logging.info("%s is audio, default format, no need to convert", path) + elif AUDIO_FORMAT is None and len(streams) >= 2: + logging.info("%s is video, default format, need to extract audio", path) + audio_stream = {"codec_name": "m4a"} + for stream in streams: + if stream["codec_type"] == "audio": + audio_stream = stream + break + ext = audio_stream["codec_name"] + new_path = path.with_suffix(f".{ext}") + run_ffmpeg(["ffmpeg", "-y", "-i", path, "-vn", "-acodec", "copy", new_path], bm) + path.unlink() + index = resp["filepath"].index(path) + resp["filepath"][index] = new_path + else: + logging.info("Not default format, converting %s to %s", path, AUDIO_FORMAT) new_path = path.with_suffix(f".{AUDIO_FORMAT}") run_ffmpeg(["ffmpeg", "-y", "-i", path, new_path], bm) path.unlink() diff --git a/ytdlbot/tasks.py b/ytdlbot/tasks.py index 58ded73..8373060 100644 --- a/ytdlbot/tasks.py +++ b/ytdlbot/tasks.py @@ -362,7 +362,7 @@ def gen_video_markup(): [ [ # First row InlineKeyboardButton( # Generates a callback query when pressed - f"convert to audio({AUDIO_FORMAT})", + "convert to audio", callback_data="convert" ) ]