pythonvideoyoutubeyt-dlp

How to extract only audio from downloading video? Python yt-dlp


I need to download only audio from youtube video. For this I use the yt-dlp tool.

In the console, I enter the following command, which downloads the audio as a .webm. I change the extension to .mp3 and everything works fine, it's a regular .mp3 file.

Command: yt-dlp --extract-audio https://www.youtube.com/watch?v=cJuO985zF8E

In the python script I'm using this code:

import yt_dlp
import os

def download_audio(link):
    with yt_dlp.YoutubeDL({'extract_audio': True}) as video:
        info_dict = video.extract_info(link, download = True)
        video_title = info_dict['title']
        print(video_title)
        #video.download(link)

download_audio('https://www.youtube.com/watch?v=cJuO985zF8E')

But the script does not load the video as an audio file, but as a video. How to solve this problem?

(sorry for my English)

I tried many methods but nothing worked.


Solution

  • I've modified and tested your code in Google Collab and it sets the name of the file with the .mp3 extension.

    Sources:

    Modified code:

    def download_audio(link):
      with yt_dlp.YoutubeDL({'extract_audio': True, 'format': 'bestaudio', 'outtmpl': '%(title)s.mp3'}) as video:
        info_dict = video.extract_info(link, download = True)
        video_title = info_dict['title']
        print(video_title)
        video.download(link)    
        print("Successfully Downloaded - see local folder on Google Colab")
    
    download_audio('https://www.youtube.com/watch?v=cJuO985zF8E')
    

    Result: a .mp3 file with the name of the YouTube video.

    KORDHELL - MEMPHIS DOOM.mp3