Nomisoft
Menu

Ffmpeg / Avconv audio conversion

18th February 2016

On a recent job for Travelodge I was asked to integrate an audio player pulling in tracks from the Spotify API. The below code demonstrates the basis of what we used for the project.

Firstly you'll need to register a new app in the Spotify Developers center to receive a Client ID and Client Secret (see https://developer.spotify.com/my-applications)

Access tokens

To be able to retrieve our playlist via the API we require authentication, this is achieved by retrieving an access token which is then passed in the headers for all subsequent requests. There are 3 methods for this, we're using the 'Client Credentials' authorization flow. There's more information about this at https://developer.spotify.com/web-api/authorization-guide/

Our first request therefore posts a 'grant_type' field set to the value 'client_credentials' to the endpoint at https://accounts.spotify.com/api/token using our base64 encoded client id and secret as a authorization header.


$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://accounts.spotify.com/api/token");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'grant_type=client_credentials');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/x-www-form-urlencoded',
    'Authorization: Basic '.base64_encode($client_id.':'.$client_secret)
));
$response = curl_exec($ch);
curl_close($ch);
$response = json_decode($response);

The response we get back is in JSON format and includes our required access token.


{
  "access_token":"XXX",
  "token_type":"Bearer",
  "expires_in":3600
}

Playlist retrieval

We can now use this access token in further requests. We know what playlist we want to retrieve so we can access this from the endpoint at https://api.spotify.com/v1/users/USERID/playlists/PLAYLIST and pass "Bearer ACCESSTOKEN" in our authorization header.


$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.spotify.com/v1/users/".$user_id."/playlists/".$playlist_id);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_HTTPHEADER,array('Authorization: Bearer '.$access_token));
$response = curl_exec($ch);
curl_close($ch);
$response = json_decode($response);

The response we get back includes all the information we need on the playlist including playlist name, urls, images, artist information, album information and most importantly the list of tracks


{
  "id" : "Playlist ID",
  "name" : "Playlist Name",
  ...
  "tracks" : {
    ...
    "items" : [ {
      ...
      "track" : {
        ...
        "artists" : [ {
          "name" : "Artist Name",
          ...
        } ],
        ...
        "name" : "Track Name",
        "preview_url" : "https://xxx",
      }
    } ],
    ....
  },
  ...
}

The complete example



<!DOCTYPE html>
<html lang="en-GB">
<head>
    <title>Spotify Test</title>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <script>
    function play(url) {
        var audioPlayer = document.getElementById('audioPlayer');
        audioPlayer.setAttribute('src', url);
        audioPlayer.load();
        audioPlayer.play();
    }
    </script>
</head>
<body>

<audio controls id="audioPlayer"></audio>

<?php
$client_id = "MY_CLIENT_ID";
$client_secret = "MY_CLIENT_SECRET";
$user_id = "MY_USERNAME"
$playlist_id = "MY_PLAYLIST_ID";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://accounts.spotify.com/api/token");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'grant_type=client_credentials');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/x-www-form-urlencoded',
    'Authorization: Basic '.base64_encode($client_id.':'.$client_secret)
));
$response = curl_exec($ch);
curl_close($ch);
$response = json_decode($response);
$access_token = $response->access_token;

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.spotify.com/v1/users/".$user_id."/playlists/".$playlist_id);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER,array('Authorization: Bearer '.$access_token));
$response = curl_exec($ch);
curl_close($ch);
$response = json_decode($response);

foreach( $response->tracks->items as $item ) {
    echo "<p onclick=\"javascript:play('".$item->track->preview_url."')\">Play ".$item->track->artists[0]->name." - ".$item->track->name."</p>";
}
?>
</body>
</html>