Learn R Programming

⚠️There's a newer version (2.2.4) of this package.Take me there.

spotifyr

Overview

spotifyr is a wrapper for pulling track audio features and other information from Spotify’s Web API in bulk. By automatically batching API requests, it allows you to enter an artist’s name and retrieve their entire discography in seconds, along with Spotify’s audio features and track/album popularity metrics. You can also pull song and playlist information for a given Spotify User (including yourself!).

Installation

Development version (recommended)

devtools::install_github('charlie86/spotifyr')

CRAN version 1.0.0 (Note: this is somewhat outdated, as it takes extra time to submit and pass CRAN checks)

install.packages('spotifyr')

Authentication

First, set up a Dev account with Spotify to access their Web API here. This will give you your Client ID and Client Secret. Once you have those, you can pull your access token into R with get_spotify_access_token().

The easiest way to authenticate is to set your credentials to the System Environment variables SPOTIFY_CLIENT_ID and SPOTIFY_CLIENT_SECRET. The default arguments to get_spotify_access_token() (and all other functions in this package) will refer to those. Alternatively, you can set them manually and make sure to explicitly refer to your access token in each subsequent function call.

Sys.setenv(SPOTIFY_CLIENT_ID = 'xxxxxxxxxxxxxxxxxxxxx')
Sys.setenv(SPOTIFY_CLIENT_SECRET = 'xxxxxxxxxxxxxxxxxxxxx')

access_token <- get_spotify_access_token()

Authorization code flow

For certain functions and applications, you’ll need to log in as a Spotify user. To do this, your Spotify Developer application needs to have a callback url. You can set this to whatever you want that will work with your application, but a good default option is http://localhost:1410/ (see image below). For more information on authorization, visit the offical Spotify Developer Guide.

Usage

What was The Beatles’ favorite key?

library(spotifyr)
beatles <- get_artist_audio_features('the beatles')
library(tidyverse)
library(knitr)

beatles %>% 
    count(key_mode, sort = TRUE) %>% 
    head(5) %>% 
    kable()
key_moden
D major24
G major21
A major13
F major12
C major11

Get your most recently played tracks

library(lubridate)

get_my_recently_played(limit = 5) %>% 
    mutate(artist.name = map_chr(track.artists, function(x) x$name[1]),
           played_at = as_datetime(played_at)) %>% 
    select(track.name, artist.name, track.album.name, played_at) %>% 
    kable()
track.nameartist.nametrack.album.nameplayed_at
Dollars & CentsRadioheadAmnesiac2019-03-11 23:16:24
Morning Bell/AmnesiacRadioheadAmnesiac2019-03-11 23:14:29
Pulk/Pull Revolving DoorsRadioheadAmnesiac2019-03-11 23:11:14
Pyramid SongRadioheadAmnesiac2019-03-11 23:07:06
TreefingersRadioheadKid A2019-03-11 23:02:17

Find your all time favorite artists

get_my_top_artists_or_tracks(type = 'artists', time_range = 'long_term', limit = 5) %>% 
    select(name, genres) %>% 
    rowwise %>% 
    mutate(genres = paste(genres, collapse = ', ')) %>% 
    ungroup %>% 
    kable()
namegenres
Radioheadalternative rock, art rock, melancholia, modern rock, oxford indie, permanent wave, rock
Onraalternative hip hop, chillhop, trip hop, wonky
Flying Lotusalternative hip hop, chillwave, electronic, escape room, experimental hip hop, glitch, glitch hop, hip hop, indietronica, intelligent dance music, wonky
Teebsabstract beats, bass music, chillwave, wonky
Aphex Twinambient, electronic, fourth world, intelligent dance music, new rave, trip hop

Find your favorite tracks at the moment

get_my_top_artists_or_tracks(type = 'tracks', time_range = 'short_term', limit = 5) %>% 
    mutate(artist.name = map_chr(artists, function(x) x$name[1])) %>% 
    select(name, artist.name, album.name) %>% 
    kable()
nameartist.namealbum.name
Illegal SmileJohn PrineJohn Prine
Shattered DreamsEarl SweatshirtSome Rap Songs
The BendsEarl SweatshirtSome Rap Songs
December 24Earl SweatshirtSome Rap Songs
LoosieEarl SweatshirtSome Rap Songs

What’s the most joyful Joy Division song?

My favorite audio feature has to be “valence,” a measure of musical positivity.

joy <- get_artist_audio_features('joy division')
joy %>% 
    arrange(-valence) %>% 
    select(track_name, valence) %>% 
    head(5) %>% 
    kable()
track_namevalence
Passover - 2007 Remaster0.941
Colony - 2007 Remaster0.808
Atrocity Exhibition - 2007 Remaster0.787
A Means to an End - 2007 Remaster0.752
Interzone - 2007 Remastered Version0.746

Now if only there was some way to plot joy…

Joyplot of the emotional rollercoasters that are Joy Division’s albums

library(ggjoy)

ggplot(joy, aes(x = valence, y = album_name)) + 
    geom_joy() + 
    theme_joy() +
    ggtitle("Joyplot of Joy Division's joy distributions", subtitle = "Based on valence pulled from Spotify's Web API with spotifyr")

Sentify: A Shiny app

This app, powered by spotifyr, allows you to visualize the energy and valence (musical positivity) of all of Spotify’s artists and playlists.

Dope stuff other people have done with spotifyr

The coolest thing about making this package has definitely been seeing all the awesome stuff other people have done with it. Here are a few examples:

Exploring the Spotify API with R: A tutorial for beginners, by a beginner, Mia Smith

Sentiment analysis of musical taste: a cross-European comparison, Paul Elvers

Blue Christmas: A data-driven search for the most depressing Christmas song, Caitlin Hudon

KendRick LamaR, David K. Laing

Vilken är Kents mest deprimerande låt? (What is Kent’s most depressing song?), Filip Wästberg

Чёрное зеркало Arcade Fire (Black Mirror Arcade Fire), TheSociety

Sente-se triste quando ouve “Amar pelos dois”? Não é o único (Do you feel sad when you hear “Love for both?” You’re not alone), Rui Barros, Rádio Renascença

Using Data to Find the Angriest Death Grips Song, Evan Oppenheimer

Hierarchical clustering of David Bowie records, Alyssa Goldberg

tayloR, Simran Vatsa

Long Distance Calling: Data Science meets Post-Rock…, Sebastian Kuhn

Copy Link

Version

Install

install.packages('spotifyr')

Monthly Downloads

899

Version

2.1.0

License

MIT + file LICENSE

Issues

Pull Requests

Stars

Forks

Maintainer

Charlie Thompson

Last Published

March 12th, 2019

Functions in spotifyr (2.1.0)

get_artist

Get Spotify catalog information for a single artist identified by their unique Spotify ID.
spotifyr

spotifyr package
get_album_data

Retrieve artist discography with song lyrics and audio info
start_my_playback

Skips to previous track in the user<U+2019>s queue.
get_category_playlists

Get a list of Spotify playlists tagged with a particular category.
add_tracks_to_playlist

Add one or more tracks to a user<U+2019>s playlist.
follow_artists_or_users

Add the current user as a follower of one or more artists or other Spotify users.
get_discography

Retrieve artist discography with song lyrics and audio info
change_playlist_details

Change a playlist<U+2019>s name and public/private state. (The user must, of course, own the playlist.)
get_featured_playlists

Get a list of Spotify featured playlists (shown, for example, on a Spotify player<U+2019>s <U+2018>Browse<U+2019> tab).
follow_playlist

Add the current user as a follower of a playlist.
get_my_followed_artists

Get the current user<U+2019>s followed artists.
get_artist_audio_features

Get audio feature information for all or part of an artists' discography.
get_my_playlists

Get a list of the playlists owned or followed by the current Spotify user.
get_playlist

Get a playlist owned by a Spotify user.
get_genre_artists

Search for artists by genre
get_artist_top_tracks

Get Spotify catalog information about an artist<U+2019>s top tracks by country.
get_my_profile

Get detailed profile information about the current user (including the current user<U+2019>s username).
get_my_recently_played

Get Current User's Recently Played Tracks
get_related_artists

Get Spotify catalog information about artists similar to a given artist. Similarity is based on analysis of the Spotify community<U+2019>s listening history.
create_playlist

Create a playlist for a Spotify user. (The playlist will be empty until you add tracks.)
get_spotify_access_token

Get Spotify Access Token
get_tracks

Get Spotify catalog information for a single track identified by its unique Spotify ID.
get_user_audio_features

Get audio feature information for a users' playlists
set_my_repeat_mode

Set the repeat mode for the user<U+2019>s playback. Options are repeat-track, repeat-context, and off.
get_playlist_cover_image

Get the current image associated with a specific playlist.
get_my_top_artists_or_tracks

Get the current user<U+2019>s top artists or tracks based on calculated affinity.
dedupe_album_names

Remove duplicate album names
set_my_volume

Set the volume for the user<U+2019>s current playback device.
get_track_audio_analysis

Get a detailed audio analysis for a single track identified by its unique Spotify ID.
get_album_tracks

Get Spotify catalog information about an album<U+2019>s tracks. Optional parameters can be used to limit the number of tracks returned.
get_new_releases

Get a list of new album releases featured in Spotify (shown, for example, on a Spotify player<U+2019>s <U+201C>Browse<U+201D> tab).
pitch_class_lookup

Pitch class notation lookup
get_albums

Get Spotify catalog information for multiple albums identified by their Spotify IDs.
get_track_audio_features

Get audio feature information for a single track identified by its unique Spotify ID.
scopes

Valid scopes
get_my_currently_playing

Get the object currently being played on the user<U+2019>s Spotify account.
toggle_my_shuffle

Toggle shuffle on or off for user<U+2019>s playback.
skip_my_playback

Skips to next track in the user<U+2019>s queue.
get_my_devices

Get information about a user<U+2019>s available devices.
skip_my_playback_previous

Skips to previous track in the user<U+2019>s queue.
get_playlist_tracks

Get full details of the tracks of a playlist owned by a Spotify user.
transfer_my_playback

Transfer playback to a new device and determine if it should start playing.
get_recommendations

Create a playlist-style listening experience based on seed artists, tracks and genres.
unfollow_playlist

Remove the current user as a follower of a playlist.
get_user_playlists

Get a list of the playlists owned or followed by a Spotify user.
get_user_profile

Get public profile information about a Spotify user.
verify_result

Verify API result
check_me_following

Check if Current User Follows Artists or Users
check_users_following

Check if Users Follow a Playlist
get_artists

Get Spotify catalog information for multiple artists identified by their Spotify IDs.
get_category

Get a single category used to tag items in Spotify (on, for example, the Spotify player<U+2019>s <U+201C>Browse<U+201D> tab).
get_spotify_authorization_code

Get Spotify authorization Code
get_track

Get Spotify catalog information for a single track identified by its unique Spotify ID.
is_uri

Check if a string matches the pattern of a Spotify URI
pause_my_playback

Pause playback on the user<U+2019>s account.
search_spotify

Search for an item
seek_to_position

Seeks to the given position in the user<U+2019>s currently playing track.
get_album

Get Spotify catalog information for a single album.
get_artist_albums

Get Spotify catalog information for multiple artists identified by their Spotify IDs.
get_my_current_playback

Get information about the user<U+2019>s current playback state, including track, track progress, and active device.
get_label_artists

Search for artists by label