const user_id = localStorage.getItem("spotify_example_user_id")
const access_token = localStorage.getItem("spotify_example_access_token")
const isPlayerPlaying = async () => {
const url = new URL(`https://api.spotify.com/v1/me/player`)
const payload = {
method: 'GET',
headers: {
'Authorization': `Bearer ${access_token}`
},
}
const body = await fetch(url, payload)
const response = await body.json()
return response.is_playing
}
const pausePlayer = async () => {
const url = new URL(`https://api.spotify.com/v1/me/player/pause`)
const payload = {
method: 'PUT',
headers: {
'Authorization': `Bearer ${access_token}`
},
}
const body = await fetch(url, payload)
}
const startPlayer = async () => {
const url = new URL(`https://api.spotify.com/v1/me/player/play`)
const payload = {
method: 'PUT',
headers: {
'Authorization': `Bearer ${access_token}`
},
}
const body = await fetch(url, payload)
}
const playPause = async () => {
const isPlaying = await isPlayerPlaying()
if (isPlaying) {
pausePlayer()
} else {
startPlayer()
}
}
document.addEventListener("DOMContentLoaded", () => {
if (user_id) {
spotifyPlayPause.addEventListener('click', playPause)
}
})