Play Music on Your Site with the Grooveshark Streaming API

Chris Coyier //

Grooveshark is a web app for listening to music. You can search for any play just about any song there is. With an account you favorite stuff, build playlists, do social stuff, you know the drill. Perhaps less known is that Grooveshark has API's that allow you to play music on your own site. This will be a tutorial and sample code to show you how that's done.

Here's the plan:

Requirements

First and foremost, you have to apply for an API key. This is not a free API. I'm not sure exactly what the costs are, so I'd recommend just applying, explaining what you are wanting to do, and they'll get in touch with you about costs. For high traffic sites, they sometimes offer hosting a grooveshark-powered advertisement as an option.

With that in hand, this is the tech we'll be using:

  1. jQuery (Ajax n' stuff)
  2. SWFObject (Embedding Flash)
  3. Grooveshark Streaming API and PHP API Wrapper
  4. Tinysong API and PHP API Wrapper

1. Embed Grooveshark Flash (SWF) onto Page

The Grooveshark Player is an (invisible) Flash embed. Once loaded onto the page, you can control it through JavaScript. Embedding it on the page is like:

  ...

  <script src="swfobject/swfobject.js"></script>
</head>

<body>

  <div id="player"></div>
  <script>
  swfobject.embedSWF("http://grooveshark.com/APIPlayer.swf", "player", "300", "300", "9.0.0", "", {}, {allowScriptAccess: "always"}, {id:"groovesharkPlayer", name:"groovesharkPlayer"}, function(e) {

    var element = e.ref;

    if (element) {

      setTimeout(function() {
        window.player = element;
        window.player.setVolume(99);
        }, 1500);

      } else {

        // Couldn't load player
        // Play sad trombone

      }

    });
    </script>

To make sure it can't be seen:

#groovesharkPlayer {
	position: absolute;
	top: -9999px;
	left: -9999px;
}

2. Having a songGetter.php

This is our local file that our page will Ajax call to request streaming information from Grooveshark. Essentially this file loads up the API wrapper and then uses it's methods to get the info we need to pass to the SWF to start playing music.

<?php

    session_start();

    // Make sure to validate and cleanse this and stuff.
    $songID = $_POST['song'];

    // Load up API wrapper
    require("gsAPI.php");
    $gsapi = new gsAPI('API-USERNAME', 'API-KEY');
    gsAPI::$headers = array("X-Client-IP: " . $_SERVER['REMOTE_ADDR']);

    // Session caching stuff
    if (isset($_SESSION['gsSession']) && !empty($_SESSION['gsSession'])) {
        $gsapi->setSession($_SESSION['gsSession']);
    } else {
        $_SESSION['gsSession'] = $gsapi->startSession();
    }
    if (!$_SESSION['gsSession']) {
        die("noSession");
    }
    if (isset($_SESSION['gsCountry']) && !empty($_SESSION['gsCountry'])) {
        $gsapi->setCountry($_SESSION['gsCountry']);
    } else {
        $_SESSION['gsCountry'] = $gsapi->getCountry();
    }
    if (!$_SESSION['gsCountry']) {
        die("noCountry");
    }

    // Make request to Grooveshark and return data as JSON
    $streamInfo = $gsapi->getStreamKeyStreamServer($songID, false);
    echo json_encode($streamInfo);
    
?>

3. Playing a Song From a Click

Let's say we have a link on our page that, when clicked, we want to fire off a song.

<a href="#" data-songid="23391593">Play This Song</a>

So with jQuery, we'll watch for that click, and fire off a custom function. We'll pass to that custom function the song ID that will pull from that links' HTML5 data attribute.

var doc = $(document);
	
doc.on("click", "a[data-songid]", function(e) {
  e.preventDefault();	
  playSong($(this).data("songid"));
});

And our custom function playSong is just an Ajax request for our own songGetter.php file that we set up:

function playSong(songID) {
	$.ajax({
	  url: "api/songGetter.php",
	  type: "POST",
	  data: {
	  	song: songID
	  },
	  success: function(response) {
	    var responseData = $.parseJSON(response);
	    window.player.playStreamKey(responseData.StreamKey, responseData.StreamServerHostname, responseData.StreamServerID);
	  }
	});
}

FANCY.

Demo

You can see this all in action:

View Demo

The demo includes the TinySong API functionality as well. This is a crucial part, as it provides the Song ID's that Grooveshark needs to identify a particular song. It would be pretty easy to combine the two API's to create search-and-play functionality, although this demo does not have that as it would require a songGetter.php file that is wide open to the internet. The particular songGetter.php file in this live demo is locked to only those few songs on the demo page.

All of this is available on GitHub.

Legal Issues

If you upload an audio file of a song directly to your server and use that to play music on your site, if that music is copyrighted, you could be in trouble. This is a way to avoid doing that, but still play that music. I am not a lawyer, but since you aren't distributing the music and the company that is pays royalties, I think you are good. If anyone knows more, feel free to share in the comments below.