free-tech

youtube to mp3


Sometimes i need to  download videos from Youtube in mp3 format. There are many websites where you can convert Youtube videos to mp3, but we will give you a simple Python script that does the same job quickly.

we are using  pytube Command-line program to download videos from YouTube.com and other video sites. It requires the Python interpreter, version 2.6, 2.7, or 3.2+, and it is not platform-specific. It should work on your Unix box, on Windows, or on macOS.

So first step is to install pytube on your system with this command line :

pip install pytube

after installing pythub here is the code to download mp3 from youtube in highest possible quality:


from pytube import YouTube
import os
from pathlib import Path


def youtube2mp3 (url,outdir):
    # url input from user
    yt = YouTube(url)

    ##@ Extract audio with 160kbps quality from video
    video = yt.streams.filter(abr='160kbps').last()

    ##@ Downloadthe file
    out_file = video.download(output_path=outdir)
    base, ext = os.path.splitext(out_file)
    new_file = Path(f'{base}.mp3')
    os.rename(out_file, new_file)
    ##@ Check success of download
    if new_file.exists():
        print(f'{yt.title} has been successfully downloaded.')
    else:
        print(f'ERROR: {yt.title}could not be downloaded!')
if __name__=='__main__':
    url = "put the url or your video here"
    outdir = "put the path where youwant the mp3 to be saved"
    youtube2mp3(url, outdir):

Put this source code in file for example youtube2mp3.py and exeute it in your terminal:

python youtube2mp3.py

#python #youtube #mp3