Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 937
404 Avatar asked Nov 17 '25 11:11

404


2 Answers

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

Sources:

  • How to rename downloaded audio files extensions to mp3 with python
  • Change the output name when download with youtube-dl using python

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
like image 89
Marco Aurelio Fernandez Reyes Avatar answered Nov 20 '25 00:11

Marco Aurelio Fernandez Reyes


"extract_audio" is not a key recognised by YoutubeDL and thus does nothing. You have to use "format": "bestaudio" instead:

# […]
with yt_dlp.YoutubeDL({"format": "bestaudio"}) as video:
# […]
like image 21
Wrzlprmft Avatar answered Nov 20 '25 01:11

Wrzlprmft



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!