Download audio from YouTube using pytube

omar harchich picture omar harchich · Mar 10, 2018 · Viewed 10.5k times · Source

I'm using pytube and Python 3.5 to download videos from YouTube but I need to convert the videos to audio with an .avi extension.

Here is my code that I'm currently working with:

from pytube import YouTube

yt = YouTube(str(input("Enter the video link: ")))
videos = yt.get_videos()

s = 1
for v in videos:
    print(str(s)+". "+str(v))
    s += 1

n = int(input("Enter the number of the video: "))
vid = videos[n-1]

destination = str(input("Enter the destination: "))
vid.download(destination)

print(yt.filename+"\nHas been successfully downloaded")

In the code above I can download a video.

My question is: How can I directly download the audio of a video on YouTube with an extension of .avi?

Can YouTube Data API help me download exclusively the audio?

Answer

Sadeny Alpha picture Sadeny Alpha · Apr 26, 2018

Upgrade your pytube, as it seems that YouTube().get_videos() is deprecated. About downloading the video: you can filter the streams for audio with a command like YouTube().streams.filter(only_audio=True).all(). Printing that function can guide you to the type of audio you want to download. In order to give it .avi format, I think you can use any converter. I'm using python 3.6.

from pytube import YouTube
yt=YouTube(link)
t=yt.streams.filter(only_audio=True).all()
t[0].download(/path)