Search code examples
pythonyoutube-dl

convert youtube-dl cmd command to python script


As I know there is two ways to convert sound.webm into sound.mp3 using youtube-dl

The first method I tried which use ffmpeg to convert the sound:

class MyLogger(object):
    def debug(self, msg):
        pass

    def warning(self, msg):
        pass

    def error(self, msg):
        print(msg)


def my_hook(d):
    if d['status'] == 'finished':
        print('Done downloading, now converting ...')

def download_sound(url):
    ydl_opts = {

        'format': 'bestaudio/best[height=360]',
        'postprocessors': [{
            'key': 'FFmpegExtractAudio',
            'preferredcodec': 'mp3',
            'preferredquality': '192',
        }],
        'logger': MyLogger(),
        'progress_hooks': [my_hook],
    }
    with youtube_dl.YoutubeDL(ydl_opts) as ydl:
        ydl.download(['https://youtu.be/A_WzVVndUCY])

file size is 8mb.

Second method:

url = 'https://youtu.be/A_WzVVndUCY'
command = ['youtube-dl', '-x', '--audio-format', 'mp3', f'{url}']

file size = 4mb.

So the second method is better for me but my question is how to convert this cmd command youtube-dl -x --audio-format mp3 $url into a python script like the first method i mention.


Solution

  • you can easily embed youtube-dl as:

    import youtube_dl
    
    ydl_opts = {}
    with youtube_dl.YoutubeDL(ydl_opts) as ydl:
        ydl.download(['https://www.youtube.com/watch?v=BaW_jenozKc'])
    

    check here for more option.