24
loading...
This website collects cookies to deliver better user experience
$ virtualenv -p python3 venv
source venv/bin/activate
pip install ytmusicapi
accept
onward didn't really work... probably because without some tweaking, the copy-paste content is an improperly formed JSON file. All you actually need for auth is the cookie, so I used the "manual file creation" method and pasted in my own cookie, and that worked fine.from ytmusicapi import YTMusic
ytmusic = YTMusic("auth_file.json")
search_results = ytmusic.search('Oasis Wonderwall')
print(search_results)
create_playlist
and add_playlist_items
. I'll try creating a test playlist, and see if it shows up in my account.from ytmusicapi import YTMusic
ytmusic = YTMusic("/home/dizzyspiral/projects/spotify-to-youtube/auth_file.json")
playlist_id = ytmusic.create_playlist(title="Test Playlist", description="Testing 1, 2, 3")
print(playlist_id)
add_playlist_items
... It requires a YouTube video ID in order to add a song, so it looks like we'll have to first search for a song, grab the corresponding music video ID, and add it to the playlist using that. But when we searched for Wonderwall, we got a bunch of results. How do we know which one is the "right" one...import csv
from ytmusicapi import YTMusic
def load_spotify_playlist(playlist_file):
songs = []
with open(playlist_file) as csvfile:
reader = csv.reader(csvfile, delimiter=',', quotechar='"')
for row in reader:
songs.append("{}{}".format(row[1], row[3]))
return songs
def search_for_songs(ytmusic, search_strings):
video_ids = []
for s in search_strings:
result = ytmusic.search(s)
video_ids.append(result[1]['videoId'])
return video_ids
if __name__ == '__main__':
print("Connecting to YouTube Music...")
ytmusic = YTMusic("auth_file.json")
playlist_file = "exported_playlist.csv"
print("Loading exported Spotify playlist...")
songs = load_spotify_playlist(playlist_file)
print("Searching for songs on YouTube...")
video_ids = search_for_songs(ytmusic, songs)
print("Creating playlist...")
# See if the playlist exists already before creating it
try:
res = ytmusic.search("Some Playlist", filter="playlists", scope="library")
playlist_id = res[0]['browseId']
except:
playlist_id = ytmusic.create_playlist("Some Playlist", "Some description")
print("Adding songs...")
for video_id in video_ids:
ytmusic.add_playlist_items(playlist_id, [video_id])
print("Done!")
add_playlist_items
takes a list of strings as an argument, for whatever reason, that doesn't actually work. It silently fails to add any songs. So, we just iterate through our list of strings, artificially making them a list of one for each API call. It takes a bit longer, but it gets the job done.