Last active
July 31, 2016 20:54
-
-
Save orrybaram/334d43ce7f5569b46c14 to your computer and use it in GitHub Desktop.
Add an embedded spotify player that plays the track your currently listening to (or last listened to) Demo at http://orryb.com/projects/currentSpotify/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var ListenWithMe = (function() { | |
// Add your own config here | |
var LASTFM_API_KEY = ""; | |
var LASTFM_USERNAME = ""; | |
// Element to inject the widget into | |
var $playerWrapper = document.getElementById('spotify-player-wrapper'); | |
return { | |
init: init | |
} | |
// Run this | |
function init() { | |
getCurrentTrack().then(function(data) { | |
var artist = data.artist['#text']; | |
var track = data.name; | |
return getTrackURI(artist, track); | |
}).then(function(data) { | |
$playerWrapper.innerHTML += buildSpotifyPlayer(data.uri); | |
}) | |
} | |
// Make a call to Last FM to get your latest played tracks; | |
function getCurrentTrack() { | |
var url = "//ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user=" + LASTFM_USERNAME + "&api_key=" + LASTFM_API_KEY + "&format=json"; | |
return new Promise(function(resolve, reject) { | |
var req = new XMLHttpRequest(); | |
req.open('GET', url); | |
req.onload = function() { | |
if (req.status == 200) { | |
var data = JSON.parse(req.response); | |
try { | |
resolve(data.recenttracks.track[0]); | |
} catch(err) { | |
reject(err); | |
} | |
} | |
else { | |
reject(Error(req.statusText)); | |
} | |
}; | |
req.onerror = function() { | |
reject(Error("Network Error")); | |
}; | |
req.send(); | |
}) | |
} | |
// Make a call to Spotify to search for the track and return the info | |
function getTrackURI(artist, trackName) { | |
var url = "//api.spotify.com/v1/search?q=track:" + trackName + "%20artist:" + artist + "&type=track" | |
return new Promise(function(resolve, reject) { | |
var req = new XMLHttpRequest(); | |
req.open('GET', url); | |
req.onload = function() { | |
if (req.status == 200) { | |
var data = JSON.parse(req.responseText); | |
try { | |
resolve(data.tracks.items[0]); | |
} catch(err) { | |
reject(err); | |
} | |
} | |
else { | |
reject(Error(req.statusText)); | |
} | |
}; | |
req.onerror = function() { | |
reject(Error("Network Error")); | |
}; | |
req.send(); | |
}) | |
} | |
// Returns an iframe with the track's URI | |
function buildSpotifyPlayer(trackUri) { | |
if(!trackUri) return; | |
return '<iframe src="https://embed.spotify.com/?uri=' + trackUri + '" width="300" height="380" frameborder="0" allowtransparency="true"></iframe>'; | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment