Skip to content
Related Articles

Related Articles

Improve Article

Automate YouTube Music to Spotify with Python

  • Last Updated : 14 Sep, 2021

Sometimes we listen to a song on YouTube music, and we really found that song interesting, and you want to add that to your Spotify playlist. Then you manually search that song, add it to the Spotify playlist. But we can automate that process of searching YouTube songs and add them into Spotify playlist using python programming. In this article, we are going to learn how we can automate the process of adding YouTube music into a Spotify playlist using Python.

Requirements:

  • Python 3 or newer should be installed on the system.
  • Youtube Data API credentials
  • Spotify API credentials
  • Youtube dl for extracting track name and artist name

Approach:

  • Firstly, we will search and list the songs in the user’s YouTube playlist using this YouTube API.
  • After saving the song information i.e. song name and artist name, we will search this information on Spotify using this Spotify API and save the data into a list.
  • In the third step, we will be creating a playlist in the user’s account using this Spotify API.
  • In the fourth and the last step, we will be traversing over the song list that we have created in step 2 and adding those songs into the playlist created in step 3 using the  Spotify API.

Note: We will be needing a Google account and a Spotify account for generating credentials to automate music from YouTube to Spotify.

Here is the YouTube playlist that we are going to sync into the Spotify music:

Youtube playlist

Stepwise implementation:

Step1: Generating credentials for Spotify API and YouTube API. Go through the following links and follow the instructions.

Generating Spotify credentials and save your user ID for future use, go to this link, you may be prompted to log in with your Spotify account details and log in. And your username is your user ID. Save this user ID on your desktop.



User id

Go to this link to generate token for authentication and click on the generate token and save this token somewhere on you’re desktop:

Saving OAuth Token

Similarly, we have to generate a YouTube OAuth token also, simply follow these instructions to generate the token.

Step 2: List all the songs from the playlist that the user wants to sync with the Spotify playlist. For that, we need to have the playlist ID of that particular playlist that we are going to sync with the Spotify playlist. 

Playlist id

Here, the highlighted one is the playlist ID. Now, we just have to list all the songs that we have in this playlist using this You search  API.

Code:

Python3




import os
import google_auth_oauthlib.flow
import googleapiclient.discovery
import googleapiclient.errors
  
  
  
def main():
    
    # Disable OAuthlib's HTTPS
    # verification when running locally.
    # *DO NOT* leave this option
    # enabled in production.
    os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"
  
    api_service_name = "youtube"
    api_version = "v3"
    client_secrets_file = "YOUR_CLIENT_SECRET_FILE.json"
  
    # Get credentials and create an API client
    flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(
        client_secrets_file, scopes)
    credentials = flow.run_console()
    youtube = googleapiclient.discovery.build(api_service_name,
                                              api_version,
                                              credentials=credentials)
  
    request = youtube.playlistItems().list(
        part="snippet",
        playlistId="PLvcDEv0bQcCgLS-OncIWVRlviC6vyZiju"
    )
    response = request.execute()
  
    print(response)
  
if __name__ == "__main__":
    main()

Output:



Step 3: After searching songs, we are going to append the title of these songs to a list, and then we are going to create a playlist on Spotify using Spotify API.

Saving song names and the artist names into a list using the information collected from step 1:

Python3




def extract_song_from_yt(dic):
    """Fetch song name from Youtube"""
  
    info = []
    song = ""
    for i in range(len(dic["items"])):
  
        video_url = url+str(dic["items"][i]["snippet"]
                            ['resourceId']['videoId'])
        details = youtube_dl.YoutubeDL(
            {}).extract_info(video_url, download=False)
        track, artist = details['track'], details['artist']
  
        info.append((track,artist))
    return info

In the above code, we have created a function that will create a list of track names and their artists. It is taking the output from the step 1 code’s output. Then we are simply using the youtube-dl library to fetch the artist name and the title of the songs, then using a for loop to append track name and artist name separated by comma to a new list called info.

Creating a new Spotify playlist:

Python3




def create_playlist():
    """Create A New Playlist"""
    request_body = json.dumps(
        {
            "name": "My New Geeks Playlist",
            "description": "Songs",
            "public": True,
        }
    )
  
    query = "https://api.spotify.com/v1/users/{}/playlists".format(
        spotify_user_id)
    response = requests.post(
        query,
        data=request_body,
        headers={
            "Content-Type": "application/json",
            "Authorization": "Bearer {}".format("spotify_token"),
        },
    )
  
    return response["id"]

In the above piece of code, we are firstly creating a simple JSON object having a playlist title description and visibility of the playlist. Then we are using Spotify playlist API to send the newly creating JSON object that has all the details of the new playlist and then returning the playlist ID of the newly generated playlist.

Step 4: After creating a new playlist on Spotify, we need to search these songs and save their Spotify URL. Let’s see how we can do that.

Generating URL for Spotify songs:

Python3






def get_spotify_uri(track, artist):
    """Search For the Song"""
  
    query = "https://api.spotify.com/v1/search?query=track%3A{}+artist%3A{}&type=track".format(
        track,
        artist
    )
    response = requests.get(
        query,
        headers={
            "Content-Type": "application/json",
            "Authorization": "Bearer {}".format("spotify_token")
        }
    )
    songs = response["tracks"]["items"]
  
    url = songs[0]["uri"]
  
    return url

Here, in the above function, we are searching for the song on Spotify using the song name and artist name. Using Spotify API we are passing track name and artist name as a parameter and then we are saving the URL of that Spotify song. We are taking the URL of the first song that comes up in our search.

Adding a song to the Spotify playlist:

Python3




def add_song(playlist_id, urls):
    """Add all songs into the new Spotify playlist"""
  
    request_data = json.dumps(urls)
  
    query = "https://api.spotify.com/v1/playlists/{}/tracks".format(
        playlist_id)
  
    response = requests.post(
        query,
        data=request_data,
        headers={
            "Content-Type": "application/json",
            "Authorization": "Bearer {}".format("spotify_token")
        }
    )
  
    return response

In the above function, are simply adding the song that we have searched to the new playlist. We are taking the playlist ID and the URLs that we have extracted using the song name and artist name as a parameter and then we dump them into a JSON object because we are going to do a post request, then simply using the Spotify add items to the playlist API.

Below is the complete implementation:

Python3




import os
import google_auth_oauthlib.flow
import googleapiclient.discovery
import googleapiclient.errors
import youtube_dl
import requests
import json
spotify_token = 'YOUR SPOTIFY TOKEN'
spotify_user_id = 'YOUR USER ID'
  
  
def get_play():
  
    # Disable OAuthlib's HTTPS verification when running locally.
    # *DO NOT* leave this option enabled in production.
    os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"
  
    api_service_name = "youtube"
    api_version = "v3"
    client_secrets_file = "YOUR_CLIENT_SECRET_FILE.json"
  
    # Get credentials and create an API client
    flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(
        client_secrets_file, scopes)
    credentials = flow.run_console()
    youtube = googleapiclient.discovery.build(
        api_service_name, api_version, credentials=credentials)
  
    request = youtube.playlistItems().list(
        part="snippet",
        playlistId="PLvcDEv0bQcCgLS-OncIWVRlviC6vyZiju"
    )
    response = request.execute()
  
    return response
  
  
def extract_song_from_yt(dic):
    """Fetch song name from Youtube"""
  
    info = []
    song = ""
    for i in range(len(dic["items"])):
  
        video_url = url+str(dic["items"][i]["snippet"]
                            ['resourceId']['videoId'])
        details = youtube_dl.YoutubeDL(
            {}).extract_info(video_url, download=False)
        track, artist = details['track'], details['artist']
  
        info.append((track, artist))
    return info
  
  
def get_spotify_uri(track, artist):
    """Search For the Song"""
  
    query = "https://api.spotify.com/v1/search?\
    query=track%3A{}+artist%3A{}&type=track".format(
        track,
        artist
    )
    response = requests.get(
        query,
        headers={
            "Content-Type": "application/json",
            "Authorization": "Bearer {}".format(spotify_token)
        }
    )
    response = response.json()
    songs = response["tracks"]["items"]
  
    url = songs[0]["uri"]
  
    return url
  
  
def create_playlist():
    """Create A New Playlist"""
    request_body = json.dumps(
        {
            "name": "My New Geeks Playlist",
            "description": "Songs",
            "public": True,
        }
    )
  
    query = "https://api.spotify.com/v1/users/{}/playlists".format(
        spotify_user_id)
    response = requests.post(
        query,
        data=request_body,
        headers={
            "Content-Type": "application/json",
            "Authorization": "Bearer {}".format(spotify_token),
        },
    )
    response = response.json()
    return response["id"]
  
  
def add_song(playlist_id, urls):
    """Add all liked songs into a new Spotify playlist"""
  
    request_data = json.dumps(urls)
  
    query = "https://api.spotify.com/v1/playlists/{}/tracks".format(
        playlist_id)
  
    response = requests.post(
        query,
        data=request_data,
        headers={
            "Content-Type": "application/json",
            "Authorization": "Bearer {}".format(spotify_token)
        }
    )
  
    return "songs added successfully"
  
  
# fething data from youtube
response = get_play()
  
# creating spotify playlist
play_id = create_playlist()
  
# getting track name and  artist name form yt
song_info = extract_song_from_yt(response)
  
# getting url for spotify songs
  
urls = []
for i in range(len(response['items'])):
    urls.append(get_spotify_uri(song_info[i][0], song_info[i][1]))
  
# adding song to new playlist
add_song(play_id, urls)

Output:

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course




My Personal Notes arrow_drop_up
Recommended Articles
Page :