Search code examples
batch-fileffmpegyoutube-dl

Convert file with any extension to MP4 with ffmpeg


I am using youtube-dl and ffmpeg to create a youtube downloader and converter (for personal use). I am trying to download a video and convert it to MP4.

The problem I have, is that youtube-dl downloads the video in a variety of formats. Is there a way that I can download the video and then tell FFMPEG to convert it, not knowing the current file type?

I tried using a * wild card but that results in an error.

@echo off
title youtube downloader

set /p name= URL: 
echo Select a type. (vid/mp3/mp4)
set /p type=

IF /i "%type%"=="vid" goto vid
IF /i "%type%"=="mp3" goto mp3
IF /i "%type%"=="mp4" goto mp4

:vid
youtube-dl %name%
goto commonexit

:mp3
youtube-dl -x --audio-format mp3 %name%
goto commonexit

:mp4
youtube-dl -o video %name%
ffmpeg -i video.* video.mp4 -hide_banner

:commonexit
pause

Solution

  • youtube-dl has this functionality built in to automatically transcode the video to another format.

    Do keep in mind that youtube-dl merges to MKV because the codecs that you downloaded the video with cannot be stored in the MP4 container. Converting to "MP4" is then a task that would require transcoding the video, which is a lossy operation and would result in further quality loss.

    If you are downloading from YouTube, it would be preferred to select formats that already support being multiplexed into an MP4 (h264/aac, instead of vp9/opus). For example, specifying the format string "bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best" would try to download the best quality video and audio that is allowed in a MP4 container. See the format selection examples for more information.

    If the video you are downloading does not have the necessary codecs available (unlikely), youtube-dl supports transcoding the video. Use the option --recode-video mp4 to somehow convert the video and audio into formats that fit into "MP4," though remember this operation does cause quality loss, and finding options that minimize the quality loss/encoding time is more of an art than a science.