Youtube to MP3 in Python

Youtube to MP3 in Python#

!pip install youtube_dl
Requirement already satisfied: youtube_dl in c:\users\meat1\anaconda3\envs\notes_env\lib\site-packages (2021.12.17)
import youtube_dl

def download_yt_as_mp3(url: str, filename: str):

    video_info = youtube_dl.YoutubeDL().extract_info(url=url, download=False)
    options = {
        'format': 'bestaudio/best',
        'preferredcodec': 'mp3',
        'keepVideo': False,
        'outtmpl': filename
    }

    with youtube_dl.YoutubeDL(options) as ydl:
        ydl.download([video_info['webpage_url']])
url = 'https://www.youtube.com/watch?v=TSvrjjdIgDw'
filename = 'leftherian-archipelago-night.mp3'

download_yt_as_mp3(url, filename)
[youtube] TSvrjjdIgDw: Downloading webpage
ERROR: Unable to extract uploader id; please report this issue on https://yt-dl.org/bug . Make sure you are using the latest version; see  https://yt-dl.org/update  on how to update. Be sure to call youtube-dl with the --verbose flag and include its complete output.
---------------------------------------------------------------------------
RegexNotFoundError                        Traceback (most recent call last)
File c:\Users\meat1\anaconda3\envs\notes_env\Lib\site-packages\youtube_dl\YoutubeDL.py:815, in YoutubeDL.__handle_extraction_exceptions.<locals>.wrapper(self, *args, **kwargs)
    814 try:
--> 815     return func(self, *args, **kwargs)
    816 except GeoRestrictedError as e:

File c:\Users\meat1\anaconda3\envs\notes_env\Lib\site-packages\youtube_dl\YoutubeDL.py:836, in YoutubeDL.__extract_info(self, url, ie, download, extra_info, process)
    834 @__handle_extraction_exceptions
    835 def __extract_info(self, url, ie, download, extra_info, process):
--> 836     ie_result = ie.extract(url)
    837     if ie_result is None:  # Finished already (backwards compatibility; listformats and friends should be moved here)

File c:\Users\meat1\anaconda3\envs\notes_env\Lib\site-packages\youtube_dl\extractor\common.py:534, in InfoExtractor.extract(self, url)
    533 self.initialize()
--> 534 ie_result = self._real_extract(url)
    535 if self._x_forwarded_for_ip:

File c:\Users\meat1\anaconda3\envs\notes_env\Lib\site-packages\youtube_dl\extractor\youtube.py:1794, in YoutubeIE._real_extract(self, url)
   1782 owner_profile_url = microformat.get('ownerProfileUrl')
   1784 info = {
   1785     'id': video_id,
   1786     'title': self._live_title(video_title) if is_live else video_title,
   1787     'formats': formats,
   1788     'thumbnails': thumbnails,
   1789     'description': video_description,
   1790     'upload_date': unified_strdate(
   1791         microformat.get('uploadDate')
   1792         or search_meta('uploadDate')),
   1793     'uploader': video_details['author'],
-> 1794     'uploader_id': self._search_regex(r'/(?:channel|user)/([^/?&#]+)', owner_profile_url, 'uploader id') if owner_profile_url else None,
   1795     'uploader_url': owner_profile_url,
   1796     'channel_id': channel_id,
   1797     'channel_url': 'https://www.youtube.com/channel/' + channel_id if channel_id else None,
   1798     'duration': duration,
   1799     'view_count': int_or_none(
   1800         video_details.get('viewCount')
   1801         or microformat.get('viewCount')
   1802         or search_meta('interactionCount')),
   1803     'average_rating': float_or_none(video_details.get('averageRating')),
   1804     'age_limit': 18 if (
   1805         microformat.get('isFamilySafe') is False
   1806         or search_meta('isFamilyFriendly') == 'false'
   1807         or search_meta('og:restrictions:age') == '18+') else 0,
   1808     'webpage_url': webpage_url,
   1809     'categories': [category] if category else None,
   1810     'tags': keywords,
   1811     'is_live': is_live,
   1812 }
   1814 pctr = try_get(
   1815     player_response,
   1816     lambda x: x['captions']['playerCaptionsTracklistRenderer'], dict)

File c:\Users\meat1\anaconda3\envs\notes_env\Lib\site-packages\youtube_dl\extractor\common.py:1012, in InfoExtractor._search_regex(self, pattern, string, name, default, fatal, flags, group)
   1011 elif fatal:
-> 1012     raise RegexNotFoundError('Unable to extract %s' % _name)
   1013 else:

RegexNotFoundError: Unable to extract uploader id; please report this issue on https://yt-dl.org/bug . Make sure you are using the latest version; see  https://yt-dl.org/update  on how to update. Be sure to call youtube-dl with the --verbose flag and include its complete output.

During handling of the above exception, another exception occurred:

DownloadError                             Traceback (most recent call last)
Cell In[6], line 4
      1 url = 'https://www.youtube.com/watch?v=TSvrjjdIgDw'
      2 filename = 'leftherian-archipelago-night.mp3'
----> 4 download_yt_as_mp3(url, filename)

Cell In[1], line 5, in download_yt_as_mp3(url, filename)
      3 def download_yt_as_mp3(url: str, filename: str):
----> 5     video_info = youtube_dl.YoutubeDL().extract_info(url=url, download=False)
      6     options = {
      7         'format': 'bestaudio/best',
      8         'preferredcodec': 'mp3',
      9         'keepVideo': False,
     10         'outtmpl': filename
     11     }
     13     with youtube_dl.YoutubeDL(options) as ydl:

File c:\Users\meat1\anaconda3\envs\notes_env\Lib\site-packages\youtube_dl\YoutubeDL.py:808, in YoutubeDL.extract_info(self, url, download, ie_key, extra_info, process, force_generic_extractor)
    804     if not ie.working():
    805         self.report_warning('The program functionality for this site has been marked as broken, '
    806                             'and will probably not work.')
--> 808     return self.__extract_info(url, ie, download, extra_info, process)
    809 else:
    810     self.report_error('no suitable InfoExtractor for URL %s' % url)

File c:\Users\meat1\anaconda3\envs\notes_env\Lib\site-packages\youtube_dl\YoutubeDL.py:824, in YoutubeDL.__handle_extraction_exceptions.<locals>.wrapper(self, *args, **kwargs)
    822     self.report_error(msg)
    823 except ExtractorError as e:  # An error we somewhat expected
--> 824     self.report_error(compat_str(e), e.format_traceback())
    825 except MaxDownloadsReached:
    826     raise

File c:\Users\meat1\anaconda3\envs\notes_env\Lib\site-packages\youtube_dl\YoutubeDL.py:628, in YoutubeDL.report_error(self, message, tb)
    626     _msg_header = 'ERROR:'
    627 error_message = '%s %s' % (_msg_header, message)
--> 628 self.trouble(error_message, tb)

File c:\Users\meat1\anaconda3\envs\notes_env\Lib\site-packages\youtube_dl\YoutubeDL.py:598, in YoutubeDL.trouble(self, message, tb)
    596     else:
    597         exc_info = sys.exc_info()
--> 598     raise DownloadError(message, exc_info)
    599 self._download_retcode = 1

DownloadError: ERROR: Unable to extract uploader id; please report this issue on https://yt-dl.org/bug . Make sure you are using the latest version; see  https://yt-dl.org/update  on how to update. Be sure to call youtube-dl with the --verbose flag and include its complete output.