download only audio from youtube video using youtube-dl in python script

前端 未结 2 837
温柔的废话
温柔的废话 2020-11-28 21:55

There\'s a few posts on downloading audio from YouTube using youtube-dl, but none of them are concrete or too helpful. I\'m wondering what the best way to do it

2条回答
  •  臣服心动
    2020-11-28 21:58

    Use postprocessors argument. The list of all the available postprocessors can be found here.

    If you want to pass additional ffmpeg or avconv options, which are not included in youtube-dl library (like audio bitrate - -ar
    in ffmpeg), add postprocessor_args as a list.

    You can also prefer ffmpeg over avconv setting prefer_ffmpeg to True.

    And to keep both original and converted audio file set 'keepvideo' to True.

    For example:

    from __future__ import unicode_literals
    import youtube_dl
    
    ydl_opts = {
        'format': 'bestaudio/best',
        'postprocessors': [{
            'key': 'FFmpegExtractAudio',
            'preferredcodec': 'wav',
            'preferredquality': '192'
        }],
        'postprocessor_args': [
            '-ar', '16000'
        ],
        'prefer_ffmpeg': True,
        'keepvideo': True
    }
    
    with youtube_dl.YoutubeDL(ydl_opts) as ydl:
        ydl.download(['http://www.youtube.com/watch?v=BaW_jenozKc'])
    

    The list of all the available options is in the documentation. You can read ffmpeg posprocessor's code here.

    And a less complex example is in their GitHub README.

提交回复
热议问题