home ~ projects ~ socials

Spotify API: Play/Pause A Track

TODO

    Get the current state

    If it's playing, pause it

    If it's not playing, start it

JavaScript

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)
  }
})
-- end of line --