Skip to content

Instantly share code, notes, and snippets.

@thelinmichael
Last active August 29, 2015 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thelinmichael/0435aa817817d415079d to your computer and use it in GitHub Desktop.
Save thelinmichael/0435aa817817d415079d to your computer and use it in GitHub Desktop.
Spotify Apps API 1.x: Printing player positions after changing track
require(["$api/models"], function(models) {
var getPosition = function(callback) {
models.player.load("position")
.done(function(player) {
callback(null, player.position);
})
.fail(function(error) {
callback(error);
});
};
var changeTrack = function(uri, callback) {
console.log("Changing track to " + uri);
models.player.playTrack(models.Track.fromURI(uri))
.done(function() {
callback();
})
.fail(function(error) {
callback(error);
});
}
var handleError = function(error) {
if (error) {
throw new Error("An error occurred while loading the position", error);
}
};
var handleChange = function(event) {
printPosition();
};
var printPosition = function(callback) {
getPosition(function(error, position) {
handleError(error);
console.log("The current position is " + models.player.position);
if (callback) {
callback();
}
});
};
var printCurrentlyPlayingTrack = function(callback) {
models.player.load("track")
.done(function(player) {
console.log("Currently playing track is " + models.player.track.uri);
callback();
})
.fail(function(error) {
callback(error);
});
};
var printInitial = function(callback) {
printCurrentlyPlayingTrack(function() {
printPosition(function() {
callback();
});
});
};
models.player.addEventListener('change', handleChange);
// Print the initial position
printInitial(function() {
// Change to a different track -- The event listener will print the new position
var trackUri = "spotify:track:27H6Luq76clxdaGT5iZH0m";
changeTrack(trackUri, function(error) {
handleError(error);
console.log("Changed track");
// Reset track -- The event listener will print the new position
var someOtherTrackUri = "spotify:track:5hxDTiXcMrDC6HluDvotfj";
changeTrack(someOtherTrackUri, function(error) {
handleError(error);
console.log("Reset track");
});
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment