How to create an online radio using jQuery and jPlayer

Who does not like music? Today, I'm glad to show you how you can use jQuery and the jPlayer plugin to build an online radio using JavaScript, PHP and a MySQL database.


Getting started

Creating the database

First, create a new SQL database. Let’s call it radio. Once done, we have to create a table. We only need 4 fields: An id, the mp3 url, the artist name and the song title. Here is the SQL code to use in order to create the table named songs:

CREATE TABLE `songs` (
  `song_id` int(11) NOT NULL AUTO_INCREMENT,
  `url` varchar(500) NOT NULL,
  `artist` varchar(250) NOT NULL,
  `title` varchar(250) NOT NULL,
  PRIMARY KEY (`song_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;

We now have a database and a table to store basic information about songs we’re going to play on our radio. Now we have to populate the table. Choose some mp3 files and insert the following statement into your database:

INSERT INTO `songs` (`song_id`, `url`, `artist`, `title`) VALUES ('', 'http://mysongs.com/songurl.mp3', 'Artist name', 'Song name');
INSERT INTO `songs` (`song_id`, `url`, `artist`, `title`) VALUES ('', 'http://mysongs.com/anothersongurl.mp3', 'Another artist', 'Another song');
INSERT INTO `songs` (`song_id`, `url`, `artist`, `title`) VALUES ('', 'http://mysongs.com/onemoresongurl.mp3', 'One more artist', 'One more song');

Right now, the database is ready.

Creating the HTML

Of course, we have to create a HTML page. First, grab your copy of jPlayer, the jQuery plugin we’re going to use to create the online radio. Unzip the file, then upload the js/ and skin/ to your server.

Then, create a file named demo.html on your server and insert the following code into it:

<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>
<html xmlns='http://www.w3.org/1999/xhtml' lang='en' xml:lang='en'>
<head>
	<title>Online radio using jQuery</title>
	<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

	<link href="skin/jplayer.blue.monday.css" rel="stylesheet" type="text/css" />

	<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
	<script type="text/javascript" src="js/jquery.jplayer.min.js"></script>
</head>

<body>
	<div id="jquery_jplayer_1" class="jp-jplayer"></div>
		<div class="jp-audio">
			<div class="jp-type-single">
		    	<div id="jp_interface_1" class="jp-interface">
					<ul class="jp-controls">
						<li><a href="#" class="jp-play" tabindex="1">play</a></li>
						<li><a href="#" class="jp-pause" tabindex="1">pause</a></li>
						<li><a href="#" class="jp-stop" tabindex="1">stop</a></li>
						<li><a href="#" class="jp-mute" tabindex="1">mute</a></li>
						<li><a href="#" class="jp-unmute" tabindex="1">unmute</a></li>
					</ul>
                
					<div class="jp-progress">
						<div class="jp-seek-bar">
							<div class="jp-play-bar"></div>
						</div>
					</div>

					<div class="jp-volume-bar">
						<div class="jp-volume-bar-value"></div>
					</div>

					<div class="jp-current-time"></div>
					<div class="jp-duration"></div>
				</div>

				<div id="jp_playlist_1" class="jp-playlist">
					<ul>
						<li><strong id="artist">Artist</strong> - <span id="songname">Song name</span></li>
					</ul>
				</div>
			</div>
		</div>
	</div>
</body>

</html>    

This code has been taken from jPlayer’s demos. It is a simple html code that insert the necessary JavaScript files (jQuery + the jPlayer plugin) as well as the CSS and html used to display the music player. Right now, the player do not display correctly: We still have to use some jQuery to animate it. We’ll see that in a minute.

Getting files from the database

Now, we have to create a PHP file that will get a random song from the database, and display the file url as well as the artist and song name so we can grab it using Ajax. First, get your copy of ezSQL that I chose to use to manage my database queries. (Full ezSQl tutorial available here) Unzip the files and upload ez_sql_core.php and ez_sql_mysql.php to the server.

Once done, create a file named getsong.php on the server. Paste the following code in it:

<?php

if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'){ 
	
	include_once "ez_sql_core.php";
	include_once "ez_sql_mysql.php";
	$db = new ezSQL_mysql('db_user','db_password','db_name','db_host'); 
	
	$song = $db->get_row("SELECT * FROM songs ORDER BY RAND() LIMIT 1");
	
	$artist = $song->artist;
	$songname = $song->title;
	$url = $song->url;
	$separator = '|';
	echo $url.$separator.$artist.$separator.$songname;
} 

?> 

Nothing complicated: I’ve included the ezSQL files needed, created a connection to the database, then requested one row from the songs table. The 3 values (File url, artist, and song name) are displayed on screen, separated by a pipe.

The conditional statement is used to detect Ajax requests and prevent people from being able to display songs url by simply typing http://www.yousite.com/getsong.php on their browser address bar.

Making it work

Alright, we’re almost done. What we need now is to use some jQuery to request a song using Ajax and our getsong.php file. Then, we’ll use jPlayer to play it.

Open your demo.html and paste the following after line 10:

<script type="text/javascript">
//<![CDATA[

$(document).ready(function(){
	$("#jquery_jplayer_1").jPlayer({
		ready: function () {
			var data = $.ajax({
			  url: "getsong.php",
			  async: false
			 }).responseText;
			
		    var string = data.split('|');
			$(this).jPlayer("setMedia", {
				mp3: string[0]
			}).jPlayer("play");
                
			$('#artist').html(string[1]);
			$('#songname').html(string[2]);
		},
		ended: function (event) {  
			var data = $.ajax({
			  url: "getsong.php",
			  async: false
			 }).responseText;
			
		    var string = data.split('|');
			$(this).jPlayer("setMedia", {
				mp3: string[0]
			}).jPlayer("play");
                
			$('#artist').html(string[1]);
			$('#songname').html(string[2]);
	    },
		swfPath: "js",
		supplied: "mp3"
	});
});
//]]>
</script>

Now, if you save the file and point your browser to http://www.yoursite.com/demo.html, your radio should work: It gets a song from the database and play it. When the song’s over, another one is automatically selected.

There’s probably better ways to write this code (It has a lot of redundant code, which is always a bad practice) so don’t hesitate to write a comment if you have a better version to suggest.

How to enhance the script

While we have a working radio, it is very basic and can be enhanced: For example, we should exclude song already played (using songs ids stored in the database) or even better, create playlists. I haven’t worked on it yet, but if you are interested let me know in a comment and I might write a tutorial about it.

Enjoyed this article? Please consider donating: 3FVR5qaxYV8yAgNUUS7FC3o8c54YfDR5zK