使用PythonYouTube Music 自动化到 Spotify
有时我们在 YouTube 音乐上听一首歌,我们真的发现这首歌很有趣,你想把它添加到你的 Spotify 播放列表中。然后您手动搜索该歌曲,将其添加到 Spotify 播放列表中。但是我们可以自动化搜索 YouTube 歌曲的过程,并使用Python编程将它们添加到 Spotify 播放列表中。在本文中,我们将学习如何使用Python自动化将 YouTube 音乐添加到 Spotify 播放列表的过程。
要求:
- 系统上应安装Python 3 或更新版本。
- Youtube 数据 API 凭据
- Spotify API 凭据
- Youtube dl 用于提取曲目名称和艺术家姓名
方法:
- 首先,我们将使用此YouTube API搜索并列出用户YouTube 播放列表中的歌曲。
- 保存歌曲信息(即歌曲名称和艺术家姓名)后,我们将使用此Spotify API在 Spotify 上搜索此信息 并将数据保存到列表中。
- 在第三步中,我们将使用此 Spotify API 在用户帐户中创建一个播放列表。
- 在第四步也是最后一步,我们将遍历我们在第 2 步中创建的歌曲列表,并使用 Spotify API 将这些歌曲添加到在第 3 步中创建的播放列表中。
注意:我们需要一个 Google 帐户和一个 Spotify 帐户来生成凭据以将音乐从 YouTube 自动化到 Spotify。
这是我们要同步到 Spotify 音乐中的 YouTube 播放列表:
分步实施:
步骤 1:为 Spotify API 和 YouTube API 生成凭据。浏览以下链接并按照说明进行操作。
生成 Spotify 凭据并保存您的用户 ID 以备将来使用,转到此链接,系统可能会提示您使用 Spotify 帐户详细信息登录并登录。您的用户名就是您的用户 ID。将此用户 ID 保存在您的桌面上。
转到此链接以生成用于身份验证的令牌,然后单击生成令牌并将此令牌保存在桌面上的某个位置:
同样,我们也必须生成一个 YouTube OAuth 令牌,只需按照这些说明生成令牌。
步骤2:列出播放列表中用户想要与S potify播放列表同步的所有歌曲。为此,我们需要有特定的播放列表的播放列表ID,我们要同步用S potify播放列表。
这里,突出显示的是播放列表ID。现在,我们只需要使用 You search API 列出该播放列表中的所有歌曲。
代码:
Python3
import os
import google_auth_oauthlib.flow
import googleapiclient.discovery
import googleapiclient.errors
scopes = ["https://www.googleapis.com/auth/youtube.readonly"]
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()
Python3
def extract_song_from_yt(dic):
"""Fetch song name from Youtube"""
url = "https://www.youtube.com/watch?v="
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
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"]
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
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
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'
scopes = ["https://www.googleapis.com/auth/youtube.readonly"]
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"""
url = "https://www.youtube.com/watch?v="
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)
输出:
第 3 步:搜索歌曲后,我们将这些歌曲的标题附加到列表中,然后我们将使用 Spotify API 在 Spotify 上创建一个播放列表。
使用从步骤 1 收集的信息将歌曲名称和艺术家名称保存到列表中:
蟒蛇3
def extract_song_from_yt(dic):
"""Fetch song name from Youtube"""
url = "https://www.youtube.com/watch?v="
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
在上面的代码中,我们创建了一个函数来创建曲目名称及其艺术家的列表。它从第 1 步代码的输出中获取输出。然后我们简单地使用 youtube-dl 库来获取艺术家姓名和歌曲标题,然后使用 for 循环将曲目名称和艺术家姓名以逗号分隔附加到名为 info 的新列表中。
创建新的 Spotify 播放列表:
蟒蛇3
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"]
在上面的一段代码中,我们首先创建了一个简单的 JSON 对象,该对象具有播放列表标题描述和播放列表的可见性。然后我们使用 Spotify 播放列表 API 发送新创建的 JSON 对象,该对象包含新播放列表的所有详细信息,然后返回新生成的播放列表的播放列表 ID。
第 4 步:在 Spotify 上创建新的播放列表后,我们需要搜索这些歌曲并保存它们的 Spotify URL。让我们看看如何做到这一点。
为 Spotify 歌曲生成 URL:
蟒蛇3
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
在这里,在上述函数,我们使用歌曲名称和艺术家姓名在 Spotify 上搜索歌曲。使用 Spotify API,我们将曲目名称和艺术家姓名作为参数传递,然后我们将保存该 Spotify 歌曲的 URL。我们正在获取搜索中出现的第一首歌曲的 URL。
将歌曲添加到 Spotify 播放列表:
蟒蛇3
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
在上面的函数,只是将我们搜索到的歌曲添加到新的播放列表中。我们将使用歌曲名称和艺术家名称提取的播放列表 ID 和 URL 作为参数,然后将它们转储到 JSON 对象中,因为我们要执行发布请求,然后只需使用 Spotify 添加项目到播放列表 API。
下面是完整的实现:
蟒蛇3
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'
scopes = ["https://www.googleapis.com/auth/youtube.readonly"]
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"""
url = "https://www.youtube.com/watch?v="
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)
输出: