
Here our needing in the ‘pytube’ package is ended.įor the second point, exists several solution packages, but it’s a good practice when you use some package for your project is that the package should be supported right now or at least not that older than 1–2 years and perfected it shouldn’t have a lot of dependencies. Notice that this file at this moment is mp4 format, but without an image, only with the audio in it. Out_file = audio_stream.download(output_path=destination) Notice, that the ‘Youtube’ class receives only str as an URL attribute.Īfter that, we parse the streams of formats that are available, with the ‘streams’ method and filter them by audio-only through the ‘only_audio’ attribute set to True:Īudio_stream = (only_audio=True).first()Īfter that, we can download it in some destination path, or if we leave it blank it’ll download it in the base directory of the project:

We receive the URL from an input or another through an API request, it doesn’t matter now for us, and save it in a variable: So, we use the ‘Youtube’ class of the ‘pytube’ package, for downloading the audio from YouTube video. But, it’s a specific feature that needs to know when we work with that package. Surely we can create a validator and formatter of the ordinary URL into the shorter version of it or it can be in the ‘pytube’ package but I haven’t seen it. If you look carefully, you’ll see that they’re almost the same, excluding the short domain ( youtu.be instead of the usual ) and the attributes after the domain (in the short URL is only the ID of the video instead of the ‘watch’ attribute in the ordinary URL and its value which is the ID of the video itself). So we need to use this button to get the short URL format for sharing. So for downloading only audio from YouTube videos, we need to receive the URL first, and there exists some specificity: the URL must be shared, which means it must have a specific short format for using it in the ‘pytube’ class.

It has a lot of nice features like parsing all stream formats of the video (mp3, mp4, wav, WebM, WMV), and it returns them as a query streams list, if we want we can use it to show up all the streams on the page and download only one that user wants, but here we need only audio.

For that purpose, we’ll surely use the ‘pytube’ package. We can install it with the pip of course:Īnd we need to import the ‘Youtube’ class using it:įirst, we need to download an audio stream from a YouTube video, receiving only its URL. One package that I used in all my solutions is ‘pytube’, for downloading a YouTube video by URL, and not the complete video with the image but only audio from that video.
