Search code examples
python-3.xyoutube-dlvideo-subtitles

How to download YouTube video subtitles in English using youtube-dl?


I have tried to download subtitles along with the video using the following Python 3.x code. It's just not working.

Here's my code:

from __future__ import unicode_literals
import youtube_dl
ydl_opts = {
'outtmpl': '/PATH/%(title)s'+'.mp4',
'format':' (bestvideo[width>=?1080]/bestvideo)+bestaudio/best',
'subtitle': '--write-srt --sub-lang en',
}
url = input("Enter your URL: ")
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
    ydl.download([url])
print("Downloaded!")

Solution

  • You need to set 'writesubtitles': True for youtube-dl to download subtitles. Also, you should specify [ext=mp4] or the program may download .webm files which are incompatible with mp4 format. The following code solves these problems:

    from __future__ import unicode_literals
    import youtube_dl
    ydl_opts = {
    'outtmpl': '/Downloads/%(title)s_%(ext)s.mp4',
    'format': '(bestvideo[width>=1080][ext=mp4]/bestvideo)+bestaudio/best',
    'writesubtitles': True,
    'subtitle': '--write-sub --sub-lang en',
    }
    url = input("Enter your URL: ")
    with youtube_dl.YoutubeDL(ydl_opts) as ydl:
        ydl.download([url])
    print("Download Successful!")
    

    Also, make sure to keep ffmpeg.exe in your youtube-dl folder for merging video and audio files. You can get it from here.