Permalink
Browse files

add example snippet

  • Loading branch information...
1 parent fdfd858 commit 047b302f0b031abbf2ab1299de5b43b22d96b550 @Floby committed Dec 26, 2012
Showing with 84 additions and 0 deletions.
  1. +47 −0 README.md
  2. +37 −0 example/play.js
View
47 README.md
@@ -23,3 +23,50 @@ or pipe the audio data to another process like [play](http://linux.about.com/lib
The main goal is now achieved. Audio data is exposed as the Player object which behaves like a readable stream
+
+Snippet
+-------
+
+Here is a code snippet of how to play a track from spotify
+
+```js
+
+var sp = require('../lib/libspotify');
+var cred = require('../spotify_key/passwd');
+
+var session = new sp.Session({
+ applicationKey: __dirname + '/../spotify_key/spotify_appkey.key'
+});
+session.login(cred.login, cred.password);
+session.once('login', function(err) {
+ if(err) this.emit('error', err);
+
+ var search = new sp.Search('artist:"rick astley" track:"never gonna give you up"');
+ search.trackCount = 1; // we're only interested in the first result;
+ search.execute();
+ search.once('ready', function() {
+ if(!search.tracks.length) {
+ console.log('there is no track to play :[');
+ session.logout();
+ }
+
+ var track = search.tracks[0];
+ var player = session.getPlayer();
+ player.load(track);
+ player.play();
+ console.log('playing track. end in %s', track.humanDuration);
+ player.on('data', function(buffer) {
+ // buffer.length
+ // buffer.rate
+ // buffer.channels
+ // 16bit samples
+ });
+ player.once('track-end', function() {
+ console.log('track ended');
+ player.stop();
+ session.logout();
+ });
+ });
+});
+
+```
View
37 example/play.js
@@ -0,0 +1,37 @@
+var sp = require('../lib/libspotify');
+var cred = require('../spotify_key/passwd');
+
+var session = new sp.Session({
+ applicationKey: __dirname + '/../spotify_key/spotify_appkey.key'
+});
+session.login(cred.login, cred.password);
+session.once('login', function(err) {
+ if(err) this.emit('error', err);
+
+ var search = new sp.Search('artist:"rick astley" track:"never gonna give you up"');
+ search.trackCount = 1; // we're only interested in the first result;
+ search.execute();
+ search.once('ready', function() {
+ if(!search.tracks.length) {
+ console.log('there is no track to play :[');
+ session.logout();
+ }
+
+ var track = search.tracks[0];
+ var player = session.getPlayer();
+ player.load(track);
+ player.play();
+ console.log('playing track. end in %s', track.humanDuration);
+ player.on('data', function(buffer) {
+ // buffer.length
+ // buffer.rate
+ // buffer.channels
+ // 16bit samples
+ });
+ player.once('track-end', function() {
+ console.log('track ended');
+ player.stop();
+ session.logout();
+ });
+ });
+});

0 comments on commit 047b302

Please sign in to comment.