Music Timer

How It Works

Wall of text incoming!

   First, I created a Spotify Developer account and created an app on it. Spotify gave me an Application ID and Application Secret to use. Then, I used Express.js to create a Node server. Express.js created the barebones of my app for me. I added in basic routing and used the "Request" library to handle gets and posts to Spotify's API.

   The first call is to authorize and get an access token, which is then used in the header of all subsequent calls. I request certain permissions from the Spotify user through "scopes". After authorization, I use the access token to retrieve a list of their playlists and put it into a multiselect list, which is part of the form, along with the hours, minutes, and seconds inputs.

   When they submit that form with the data, the server finds a playlist through my algorithm. It puts all the songs in all selected playlists into a set, so there are no duplicates (since playlists shouldn't have two of the same song). Each song in the set also has its duration (in milliseconds) and URI in a JSON object attached to it. Two checks are performed before the algorithm is run. The first one adds up all the durations to make sure that it's possible to hit the required time with the playlists given. If not, it finishes with the error "Not enough songs". The second check, which happens at the same time, makes sure that the required time isn't shorter than any one song. If it is, the program finishes with the error "Songs too long". After both checks are cleared, the algorithm is called.

   It randomizes the set of songs and then starts from the first one. It keeps adding songs until the total exceeds the required time. If it's not close enough (my algorithm has a leniency of 1 second), it will eliminate the second song or the first song and try again. This branching continues until it finds one close enough. For example, assume you have the 5 songs: 0, 1, 2, 3, 4. It tries 0, then 0 1, then 0 1 2, then 0 1 2 3. Uh oh, it went over, and it's longer by more than a second. Now it will try 0 2, then 0 2 3, then 0 2 3 4 and 1 2, then 1 2 3, then 1 2 3 4 simultaneously. Once it finds the first list that is close enough to the required time, it breaks.

    Another call to the Spotify API is made to create the new playlist. There is another call right afterwards to add the songs to the playlist using the URIs that were in the set. The result page is rendered, and the program is done!

    The front end was created using Pure CSS and Bootstrap.