How to get video duration by youtube-dl in python?
Asked Answered
N

2

5

I'm trying to get youtube video duration by using youtube-dl in python. here is the code, I cant find duration in dictMeta, how to get it?

    import youtube_dl

    ydl_opts = {
    'format': 'bestaudio/best',
    'outtmpl': 'tmp/%(id)s.%(ext)s',
    'noplaylist': True,
    'quiet': True,
    'prefer_ffmpeg': True,
    'logger': MyLogger(),
    'audioformat': 'wav',
    'forceduration':True
}
sID = "t99ULJjCsaM"
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
    dictMeta = ydl.extract_info(
        "https://www.youtube.com/watch?v={sID}".format(sID=sID),
        download=True)
Noblesse answered 23/10, 2018 at 10:33 Comment(0)
O
9

just simple

dictMeta['duration']
Overcoat answered 23/10, 2018 at 11:19 Comment(3)
Does youtube-dl provides us with durations in miliseconds or do we have to convert that ourselves?Reverence
For @keanu_reevers , how I find out. Video: Hank Green, vlogbrothers, "Honest YouTube Talk Time", CC Attribution License (reuse allowed); known video length: 00:03:56 = 236 seconds = 236000 ms . Experiment time! Experiment 1, interactive python prompt: OP's code example, without 'logger': MyLogger(),, with sID = "cRWr4VNqIjY". (From python's interactive terminal, I actually get 3:56 returned, though I'm not sure from where.) Using the answer from Macio, INPUT: >>>dictMeta['duration'] OUTPUT: 236. ANSWER: youtube-dl DOESN'T provide us durations in ms; it provides seconds.Catt
Experiment 2, bash command-line version of youtube-dl: INPUT: $ youtube-dl --get-duration "https://www.youtube.com/watch?v=cRWr4VNqIjY" OUTPUT: 3:56. Even more conversion will be needed.Catt
P
1

I think youtube_dl changes the result string by extract_info, now it should be: (If you use "ytsearch" for searching query on Youtube)

dictMeta['entries'][0]['duration']
Picket answered 29/11, 2021 at 21:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.