diff --git a/lib/track.js b/lib/track.js index 1536df8..622d737 100644 --- a/lib/track.js +++ b/lib/track.js @@ -73,13 +73,28 @@ Track.prototype.metadata = function (fn) { /** * Begins playing this track, returns a Readable stream that outputs MP3 data. * + * @param {Function} fn callback function * @api public */ -Track.prototype.play = function () { +Track.prototype.play = function (fn) { // TODO: add formatting options once we figure that out var spotify = this._spotify; - var stream = new PassThrough(); + var returnValue = undefined; + + // Maintain old compatibility + if ('function' !== typeof fn) { + var stream = new PassThrough(); + fn = function (err, res) { + if (err) { + stream.emit('error', err); + } else { + res.pipe(stream); + } + }; + // return stream immediately so it can be .pipe()'d + returnValue = stream; + } // if a song was playing before this, the "track_end" command needs to be sent var track = spotify.currentTrack; @@ -93,8 +108,8 @@ Track.prototype.play = function () { // initiate a "play session" for this Track spotify.trackUri(track, function (err, res) { - if (err) return stream.emit('error', err); - if (!res.uri) return stream.emit('error', new Error('response contained no "uri"')); + if (err) return fn(err); + if (!res.uri) return fn(new Error('response contained no "uri"')); debug('GET %s', res.uri); track._playSession = res; var req = spotify.agent.get(res.uri) @@ -107,14 +122,13 @@ Track.prototype.play = function () { function response (res) { debug('HTTP/%s %s', res.httpVersion, res.statusCode); if (res.statusCode == 200) { - res.pipe(stream); + fn(null, res); } else { - stream.emit('error', new Error('HTTP Status Code ' + res.statusCode)); + fn(new Error('HTTP Status Code ' + res.statusCode)); } } - // return stream immediately so it can be .pipe()'d - return stream; + return returnValue; }; /**