Search code examples
pythonyoutubepython-removiepypytube

Download Youtube playlist as mp3 in Python


I'm trying to download my video playlist and convert it to mp3 extension using pytube,moviepy,re. Everything works but when it hits a number it stops working.

How can I fix this?

from pytube import YouTube
from pytube import Playlist
import os
import moviepy.editor as mp #to convert the mp4 to wav then mp3
import re

playlist = Playlist("https://www.youtube.com/playlist?list=PLb2p41g_hNVOeBy3OjGTdXKgscedya9f_")

for url in playlist:
    print(url)
for vid in playlist.videos:
    print(vid)
for url in playlist:
    YouTube(url).streams.filter(only_audio=True).first().download("./Downloads/Music_2")
folder = "./Downloads/Music_2"
for file in os.listdir(folder):
    if re.search('mp4', file):
        print("Converting: " + file)
        mp4_path = os.path.join(folder,file)
        mp3_path = os.path.join(folder,os.path.splitext(file)[0]+'.mp3')
        new_file = mp.AudioFileClip(mp4_path)
        new_file.write_audiofile(mp3_path)
        os.removed(mp4_path)

Error Code;

Traceback (most recent call last):
  File "C:\Users\user\Downloads\Projects\Python\main.py", line 14, in <module>
    YouTube(url).streams.filter(only_audio=True).first().download("./Downloads/Music_3")
    ^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\user\Downloads\Projects\Python\venv\Lib\site-packages\pytube\__main__.py", line 296, in streams
    return StreamQuery(self.fmt_streams)
                       ^^^^^^^^^^^^^^^^
  File "C:\Users\user\Downloads\Projects\Python\venv\Lib\site-packages\pytube\__main__.py", line 176, in fmt_streams
    stream_manifest = extract.apply_descrambler(self.streaming_data)
                                                ^^^^^^^^^^^^^^^^^^^
  File "C:\Users\user\Downloads\Projects\Python\venv\Lib\site-packages\pytube\__main__.py", line 161, in streaming_data
    return self.vid_info['streamingData']
           ~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^
KeyError: 'streamingData'

Process finished with exit code 1

Solution

  • Just try this one - This will download the entire playlist as webm which basically can be played as mp3, therefor I'm setting the outtmpl as TITLE.mp3 (to the current folder)

    enjoy :)

    from yt_dlp import YoutubeDL
    
    if __name__ == '__main__':
        video_url = input("Please insert the URL: ")
        video_info = YoutubeDL().extract_info(url=video_url, download=False)
        options = {
            'format': 'bestaudio/best',
            'keepvideo': False,
            'outtmpl': '%(title)s.mp3',
            # 'playlist_items': '2'
        }
        with YoutubeDL(options) as ydl:
            out = ydl.download([video_info['webpage_url']])