We available for hire! — Need help with a web or mobile project?
From yensdesign we develop technology projects based on web apps, mobile apps, consulting and databases. We are young and hard workers, passionate about innovation and focused in new technologies.If you want to ask for a budget, we hare available for hire!.
Playing and Controlling MP3 songs and FLV videos with javascript
January 20th, 2009Hi there guys! If you remember we have published a tutorial about How to create a music player interface in jQuery some weeks ago. Some of you have sent me e-mails, posted comments in the tutorial and in our forums asking about how to implement “the music” to the music player interface. And now I am here to show you the basics to acomplish it.
We are going to learn how to Load, Play and Control our MP3 songs and FLV videos to share them with our visitors in our websites by using javascript (some jQuery) and the flash player JW Player.
As always, you can try the living example over here.
Tested in: Firefox, Internet Explorer 6 & 7, Opera, Safari & Chrome.
Come on with me guys!
What, Why & How?
What? As I told you we are going to create a player that will allow us play MP3 files, FLV videos and more… But there are more file formats that you can load and play following this tutorial:
- FLV7 & 8 video
- H.264 video
- Youtube video
- MP3 audio
- AAC audio
- JPG, GIF & PNG images
Why? Some people want to know how to show their music, their videos… and so on, or just want to implement the music factor to our old tutorial about music player and mouse gestures.
How? As always, we are going to use our lovely javascript library jQuery and the flash player JW Player.
- Javascript will be used for: Load and Control the flash player.
- JW Player will be used for: Load and Play our desired files, in this example MP3 songs and FLV videos.
So let’s dive into the layout!
Step 1: The Layout
One more time we are going to focus in the main goal: load and play our multimedia files, so we are going to create a simple and clean layout with two main divisions: #player1 and #player2:
[code language="html"][/code]Playing mp3 files
Playing FLV files
Nothing special, right? As you can see it’s a simple layout.
We are going to place our two players (one for the MP3 song and one for the FLV video) in these two divisions: #player1 and #player2.
Let’s add some style guys.
Step 2: Adding style to our example
We are going to apply the same style than in previous tutorials, using first of all our reset CSS snippet:
[code language="css"] @CHARSET "UTF-8"; /******* GENERAL RESET *******/ html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, font, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td { border: 0pt none; font-family: inherit; font-size: 100%; font-style: inherit; font-weight: inherit; margin: 0pt; padding: 0pt; vertical-align: baseline; } body{ line-height: 14px; font-size: 12px; background: #fff; font-family: Tahoma, Verdana, Arial, Helvetica, sans-serif; margin: 0pt; cursor: default; } table{ border-collapse: separate; border-spacing: 0pt; } caption, th, td{ font-weight: normal; text-align: left; } blockquote:before, blockquote:after, q:before, q:after{ content: ""; } blockquote, q{ quotes: "" ""; } input, textarea, select{ font-family: Tahoma, Verdana, Arial, Helvetica, sans-serif; font-size: 11px; } strong{ font-weight: 700; } ul{ list-style: outside; } a{ cursor: pointer; color: #296ba5; text-decoration: none; } .clear{ clear: both; height: 0; visibility: hidden; display: block; } /******* /GENERAL RESET *******/ h1{ font-weight: 700; font-size: 18px; line-height: 1.2em; border-bottom: 1px dotted #6b9ef1; color: #5f95ef; margin-bottom: 1em; } /******* LOGO *******/ #logo{ text-align: center; margin-top: 1em; display: block; } /******* /LOGO *******/ /******* CONTAINER *******/ #container{ width: 600px; margin: 40px auto; text-align: left; } /******* /CONTAINER *******/ /******* CONTENT *******/ div.content span{ display: block; font-weight: 700; color: #898989; margin-top: 10px; } div.content{ padding: 0 10px 20px 30px; margin-bottom: 20px; } div.content a{ margin: 0 4px 0 4px; color: #9a9a9a; } div.content a:hover{ color: #5f95ef; text-decoration: underline; } div.content div.status{ font-size: 10px; border-bottom: 1px solid #a5a5a5; margin-bottom: 4px; color: #5f95ef; } #player2{ margin-bottom: 10px; } /******* /CONTENT *******/ [/code]
All right guys, just continue reading. Now here comes the interesting part
Step 3: Adding and Controlling our players with jQuery
One more time our javascript part will be done in jQuery. As you have seen in the HTML layout, we are including 3 javascript files:
- swfobject.js: Flash Player detection and embed by Geoff Stearns.
- jquery.js: jQuery 1.3 version, yay!
- core.js: Here go our future code!
So we only need to setup and add our two players in our layout. We are going to follow the same process for both players:
- Create the SWF Object
- Add desired variables to this SWF Object (for example the file path)
- Place the SWF Object in the desired HTML division (#player1 & #player2)
- Create a javascript object to manage the flash player (SWF Object), so we can send events (play, pause, mute…)
- Add and manage events to some DOM elements to send events to our javascript object (to the flash player)
Mmmmm complicated? Not at all guys, don’t be afraid, it’s very very easy to understand! You will see it by taking a look at the core.js code.
Remember that all this code must be in the $().ready of jQuery!. Here you have:
[code language="javascript"] $().ready(function(){ //SETUP Mp3 files player example var playerMp3 = new SWFObject("player.swf","myplayer1","0","0","9"); playerMp3.addVariable("logo","css/images/logo.jpg"); playerMp3.addVariable("file","songs/BraveHeart.mp3"); playerMp3.addVariable("icons","false"); playerMp3.write("player1"); //create a javascript object to allow us send events to the flash player var player1 = document.getElementById("myplayer1"); var mute1 = 0; var status1 = $("#status1"); //EVENTS for Mp3 files player $("#play1").click(function(){ player1.sendEvent("PLAY","true"); status1.text("PLAYING..."); }); $("#pause1").click(function(){ player1.sendEvent("PLAY","false"); status1.text("PAUSED"); }); $("#mute1").click(function(){ if(mute1 == 0){ player1.sendEvent("mute","true"); mute1 = 1; } else{ player1.sendEvent("mute","false"); mute1 = 0; } }); //Setup FLV files player example var playerFlv = new SWFObject("player.swf","myplayer2","400","300","9"); playerFlv.addVariable("screencolor","white"); playerFlv.addVariable("image","videos/preview.jpg"); playerFlv.addVariable("file","videos/video.flv"); playerFlv.write("player2"); //create a javascript object to allow us send events to the flash player var player2 = document.getElementById("myplayer2"); var mute2 = 0; //EVENTS for FLV files player $("#play2").click(function(){ player2.sendEvent("PLAY","true"); }); $("#pause2").click(function(){ player2.sendEvent("PLAY","false"); }); $("#mute2").click(function(){ if(mute2 == 0){ player2.sendEvent("mute","true"); mute2 = 1; } else{ player2.sendEvent("mute","false"); mute2 = 0; } }); }); [/code]
Isn’t easy? I told you guys
For those who didn’t understand it, we will see a little explanation for each player.
For the MP3 player, player1:
- We have created the SWF Object and configured it up with null height and width. Why? Because we don’t want to show the flash player to our users, just our javascript controls
- We have added some variables to the object, like the MP3 file path to play, a logo at the right-top (well you can call me dumb for adding a logo to an invisible player, but it’s to see more options hehe) and more…
- We are using a free and lovely MP3 song from Sonic Mistery.
- We have used the write() method of the SWF Object to place our player in the paragraph #player1. It’s invisible because it has null width and height, but it’s there.
- Then we have created a javascript object to allow us send events to the new flash player.
- So we have added some controls to manage the player, like PLAY, PAUSE and MUTE and we are showing the current status of the player by changing values of our #status1 division.
It’s important to notice that in the MP3 player we are simulating the current status of the flash player, but it’s not the real current status. If you send events via javascript the flash player update his status, but if you make changes by using flash controls you are not able to know if there are changes in the flash player.
To have synchronized both sides, flash and javascript, we need to add listeners to our players, so we will receive an “alert” in javascript when something that we want to manage happens. You can check more about how to add listeners in the JW Player documentation.
For the FLV player, player2:
- We have created the SWF Object and configured it up with a specific height and width. Why? Because we want to show the flash player to our users, to let them see the video
- We have added some variables to the object, like the FLV file path to play, an image preview and more…
- We have used the write() method of the SWF Object to place our player in the paragraph #player2. It’s visible because it has not null width and height.
- Then we have created a javascript object to allow us send events to the new flash player.
- So we have added some controls to manage the player, like PLAY, PAUSE and MUTE but we are not showing the current status of the player because as we said, it won’t be synchronized, we need to add listeners!
And that’s all guys! Good luck with your attempts!
Step 4: Trying our players
There are a lot of variables, options and improvements that you can add to these players so I suggest you visit the official website and take a look to the documentation. I am not sure but if you want, we will make more tutorials about this stuff, about JW Player and how to control listeners and more.
Nothing more to say guys, as always you can check out the living example, and download all entire sources of our tutorial.
Ah! Special thanks too for plusmusica.com contributors that are helping us to translating it into most of common languages. We are still searching help for italian and japanese translation! If you want to help just contact with us!
Remember that you can solve your doubts in our forums and follow us on Twitter to know more about what are we doing in any moment!
Thank you so much guys, and see you in next tutorial!
One more thing…
100% guaranteed 1Y0-A17 questions prepared by certified professionals in same way to real exam. Just download the 70-290 exam dumps with 70-662 study guides and pass your certification exam on first attempt guaranteed.
Totally awesome Heart Pendant Necklaces available at LusterForever jewelers stores.
Enjoy this post?
Your vote will help us to grow this website and write more entries like this one :)
We available for hire! — Need help with a web or mobile project?
From yensdesign we develop technology projects based on web apps, mobile apps, consulting and databases. We are young and hard workers, passionate about innovation and focused in new technologies. We try to help you, sharing our knowledge acquired on worked projects, while helping the community and showing our capabilities.If you want to ask for a budget, we hare available for hire! Don't doubt in get in touch with us!.
Great tutorial Adrian!
@Estevao Thank you
Beautiful tutorial. Very helpful. Thanks.
great tutorial
So say you have the player at the top of your website, what would be the best technique (without using frames or creating a Flash website) to keep the song playing when someone navigates to a different page?
@Umut and @Markus Thank you so much!
@Morpheus Great question! And… We have already 2 tutorials published to answer your question:
http://yensdesign.com/2008/11/creating-ajax-websites-based-on-anchor-navigation/
http://yensdesign.com/2008/12/how-to-load-content-via-ajax-in-jquery/
Good luck!
DOPE! Thanks for the tutorial, can’t wait to implement it.
Stumbled for ya, forgot to mention that…
@Gabe thanks for posting! By the way, it will be great if you post in our forums that implementation http://forums.yensdesign.com/
Great tutorial!
Can you add the playlist.Where user can choose use what to be play…
[...] Playing and Controlling MP3 songs and FLV videos with javascript … [...]
This is perfect, Thanks for hard work.
Wow, what a great tut. I find my new tut favourite site!!! Awesome.
I find a cool example to see how powerful swfobject.js is under http://nonverbla.de/blog/2008/09/15/nonverblasterhover/. Much fun with that…
Cheers,
GGrag
@GGrag Thank you so much
I downloaded the source to play default flv file.
But i recieced an error : Object doesn’t suppport this property or method.
(line at : player2.sendEvent(“PLAY”,”true”);)
How I can solve this problem? Help!
Thanks so much!
@vodka As the tutorial says you need to try the demo in a web server not as local file!
Thanks Adrian Mato Gondelle so much!
It’s run successful!
Thanks!
Hi yens, it seems that the JW player is for non commercial purposes… do you know of any player that’s meant for commercial purposes and is free? It’d be great if you could give me a link or something at [email protected]; pretty please?
@Aditya I don’t know any other players at this moment… if you find someone please tell us in forums!
is there a forum on the site?
Hey, Thanks for the tutorial. I am using this to play a single mp3 file. Do you know a way to make it play automatically when the page loads? Thanks.
Great tut, tx Adrian.
Question: Is there a jquery method to save the mute state in a cookie? Also it would be cool to change the mute button appearance to reflect the mute state.
I ask because visitors want to mute the home page .flv, then navigate the site, then return to the home page. They will not want to hit mute every time the .flv loads when they return to the home page.
Best regards from Chicago.
thks for the great tutorial but i got a question !
i don’t understand why there is this line here :
var player1 = document.getElementById(“myplayer1″);
which or do i must name with their id myplayer1 ?
there are no place beside this getElementbyID with the name myplayer1
thks for the help !
sorry for my english , i am not english at all
ooooops ok i think i saw my error
sorry for the useless comment.
but it doesn’t work for me…. maybe because i got the mootools plugin too
arrg
hi, after few hours of trying, it does something that i dont understand
take here : http://www.mind-rising.com/lite/jwplayer/try.php
and here : http://www.mind-rising.com/lite/
it’s two place that i placed your great tuto but on the 1st link it work !!!
but on the second it doesn’t work
i need help !
thks
ok i think i know why it didn’t work for
it will be great to notice people that there is an order of writing the call of the .js
because if you write the call of core.js before the jquery.js it will never work
please , delete my post before this one
thks !
and btw, i got another problem that few people know i think. i use the mootools plugin for my page and it’s not compatible with the jquery.js
when i put both of them on the same xhtml page. the mootool.js dont want to work anymore
i need help ! thks
thanks for sharing! like the script. do you know why it isn’t playing in my browser? it doesn’t play all the way through. pauses after a split second.
Ummm… Why does the “fullscreen” feature doesnt work?
Hey Adrian,
Thanks for sharing your excellent work!
I tested it with JW player and it works like a charm.
But my question is can we use the same java script to control FLV using some other players?
Like:
JCPlayer (http://www.jcplayer.com)
FlowPlayer (http://flowplayer.org), etc.
Hope you can help with this…
its good to see somone discussing this problem sometimes it is so hard to come across a honest opinion and i appreciate your honesty on this concern i just wish you had a newsletter i could subscribe to as i would be really interested in readind your posts and debating on futher issues you may desire to discuss, stay blessed.
It would be nice if I could somehow define the target swf in html of the site. If I have several videos I have to make different jquery-file for each of them?
Hey there! I’m trying this example on my computer with Chrome, i’ve downloaded the sources from here. It dosen’t work. when i hit play i get this error in the javascript console : “Uncaught TypeError: Object # has no method ‘sendEvent’” . what should i do? it’s really necessary to upload the sources on a server?
hey can the audio start auto playing when the page loads? is that possible how?