File size: 1,208 Bytes
d44849f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import yt_dlp

def download_audio_from_video(url, output_path='./'):
    """Download audio from a YouTube video and save it as MP3."""
    # Set up the options for yt-dlp
    ydl_opts = {
        'format': 'bestaudio/best',  # Download the best audio quality available
        'outtmpl': f'{output_path}/%(title)s.%(ext)s',  # Set output template for the file name and path
        'noplaylist': True,  # Avoid downloading playlists
        'postprocessors': [{  # Convert the downloaded audio to MP3
            'key': 'FFmpegAudioConvertor',
            'preferredcodec': 'mp3',  # Set the preferred codec to mp3
            'preferredquality': '192',  # Set the MP3 quality (you can adjust the value if needed)
        }],
        'quiet': False  # Show progress and logs
    }

    try:
        # Download the audio using yt-dlp
        with yt_dlp.YoutubeDL(ydl_opts) as ydl:
            ydl.download([url])
        print("Download completed successfully.")
    except Exception as e:
        print(f"Error: {e}")

# Example usage
url = input("Enter YouTube video URL: ")
output_path = input("Enter output directory (default is current directory): ") or './'
download_audio_from_video(url, output_path)