This is a code submitted by user Pedro Lobito a year ago here: https://stackoverflow.com/a/60490761/874188
It should download a youtube .mp3 file based on the keywords searched.
import youtube_dl # youtube-dl-2020.3.1
import traceback, os, json
from youtube_search import YoutubeSearch # pip install youtube_search
search = 'carlos paiao playback'
ydl_opts = {
'format': 'beataudio/best',
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '192'
}]
}
yt = YoutubeSearch(search, max_results=1).to_json()
try:
yt_id = str(json.loads(yt)['videos'][0]['id'])
yt_url = 'https://www.youtube.com/watch?v='+yt_id
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
ydl.download([yt_url])
info = ydl.extract_info(yt_url)
songname = info.get('title', None) + "-" + yt_id + ".mp3"
if os.path.isfile(songname):
print("Song Downloaded: " + songname)
else:
print("Error: " + songname)
except:
pass
print(traceback.print_exc())
print("no results")
As you can test, for the example provided under search
string, it works perfectly fine. However, let's say if you put something like 'as we fall' keywords for the youtube video, os.path.isfile
will get marked as False
and downloading won't work. It appears to work 50/50, some keywords work, others not, and I have absolutely no idea why os.path.isfile
behaves like that. I tried to get in contact with original poster but my rep is too low. Original post:how to use a key words instead of a url with youtube-dl and discord.py?
EDIT 1
The reason why os.path.isfile
sometimes returns false for seemingly no reason is because the youtube titles sometimes may have characters forbidden in file names. Could this problem be somewhat fixable or is there any alternative to bypass this? My os is windows 10.
EDIT 2 Well, I'm screwed. https://superuser.com/questions/1112132/how-to-create-folder-name-or-file-name-with-special-characters-like