How to create an online radio using jQuery and jPlayer

by Jean. 34 Comments -

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.

Comments (34) - Leave yours

  1. Lutvi Avandi said:

    Is this tutorial can works with external mp3 files? I have lot of mp3 files database in 4shared, can I use them in this script? Thanks..

    About the playlist, we will love it if you want to write the tutorial for us

  2. Andrew said:

    Hey,

    thanks for this tutorial its great.
    But i have a problem. I want to open the Media File with php and the header and readfile option, so that the jplayer can play a song i opend before with the php file. is that possible ?

  3. Alex said:

    Nice tutorial. How can i exclude a song that was played?? and how can i make playlists?? Im really interested, can you make a tutorial?? Thanks

  4. Seth said:

    I did the above tutorial but the songs are not playing….

    I think I messed up creating proper (php-my-admin) table and getting the right info in there.
    I was kinda hoping just uploading all the php and sql files i downloaded from you would magically set things up for me
    once i uploaded them to my server but i guess not??

    also the demo link is broken (would be nice to study working example)

    just want to get some dialogue going and see if i can figure out what I’m doing wrong

    thanks

    • Javier said:

      Hey Seth, did you figure out what the problem was? Let me know if you managed to get the player working properly.

      Javier

  5. Ashley Sargent said:

    Hi i would like to be able to skip tracks too could you show me how to do this, i have it working on random as shown from the tutorial, but i would like next and back buttons aswell

  6. Max DeGroot said:

    Is it possible to make the player display the embedded Album Art from the mp3 while the song is being played?

    Also, yes, I want to find out about creating a playlist that can be played in order.

  7. ken said:

    I have done your tutorial just the way you have said and its not working, also your demo is not working too. has any one done the tutorial and got it working? if so can you help out Please.

  8. ken said:

    Thanks for a great tutorial, It works fine on chrome but does not work on Firefox and IE because of the file format being mp3. is there a way i can make this online radio player play “mp3, mp4, ogv, webm, ogg and m4a”? i am trying to make a video/audio player, i have video files saved on my server but this player only plays them as audio mp3s how do i change
    var string = data.split(‘|’);
    $(this).jPlayer(“setMedia”, {
    mp3: string[0]
    }).jPlayer(“play”); to play other formats?
    Please Help

  9. Zain said:

    hello,
    i m totally new in all this i m not able to do so as described above please some one do it in video and give me link i will be very thankfull to you.
    and i have 2 questions:
    1.can we do shoutcast i mean can we add Rjs to this radio by shoutcast i.e we rj shoutcast stops it automatically start playing through its own database?
    2.can we play any song instantly from database like on request?
    if these two things can b done then please include it in the video please it a humble request i actually want to make a free radio live 24/7 website any help will be highly appreciated.

    • Risky Pathak said:

      Hey roger.. below is the raw code i have used to avoid repeats… Hope this helps…

      MYSQL:
      alter table songs add is_played TINYINT(1)
      update songs set is_played = 0

      PHP:
      0)
      {
      $songid = mysql_result($result, 0, “song_id”);
      $artist = mysql_result($result, 0, “artist”);
      $songname = mysql_result($result, 0, “title”);
      $url = mysql_result($result, 0, “url”);
      mysql_close();

      $separator = ‘|’;
      echo $url.$separator.$artist.$separator.$songname;

      //Update row for this song
      mysql_connect($db_server, $db_user, $db_passwd);
      @mysql_select_db($db_name) or die(“Unable to select database”);
      mysql_query(“UPDATE songs SET is_played=1 WHERE song_id = “.$songid);
      mysql_close();
      }
      //If alll songs has been played then reset isplayed for all rows
      else
      { mysql_connect($db_server, $db_user, $db_passwd);
      @mysql_select_db($db_name) or die(“Unable to select database”);
      mysql_query(“UPDATE songs SET is_played=0″);
      mysql_close();

      // send song for this request too….
      sendsong();
      }

      }
      //}
      /*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;
      } */

      ?>

Leave a Reply

Your email address will not be published. Required fields are marked *

Please respect the following rules: No advertising, no spam, no keyword in name field. Thank you!