How It’s Made: Youtube player in Java

Few of you asked, so here is how …

First of all, you need a way to search Youtube and get url of some video. And that is really simple since there is an official Google Data API for using some of the services Google offers, and there is an open source GData Java Client Library, and great tutorials and examples of how to use it.

So, for example, from a query for ‘Revolucion Movie Library’ you will get a List of VideoEntries. And from VideoEntry you can get stuff like video title, location, type, url, duration, thumbnails etc. Video location is a string like “http://www.youtube.com/v/9yi9EdbYaFc&…”. Remember that :)

Now we need to play that somehow …

If you have a right codec, youtube video can be played in probably any video player – try opening above url (that you remembered :)) in Windows Media Player. But there are problems, at least I had them. First, that seems now is gone (probably fixed in newer versions of WMP or Flash), you couldn’t interact with a video, so you couldn’t click ‘Play’. That can be resolved by appending “&autoplay=1″ to url, but than you can’t stop it. And, there comes a second problem – you can’t even really stop it with “Stop” button in your player. I first written a wrapper around WMP so I can use it in Swing, but that did’t work quite well. Also I tried JMC, but it crashed from time to time.

Other solution is playing Youtube videos in web browser. And this way you can even use a chromeless player (“… by definition, a YouTube video with no controls”), and control it using JavaScript. And if we had JWebPane this would be excellent. But since it isn’t finished yet … there are alternatives: WebBrowser from JDIC project, WebBrowser from JDICplus, …, and JWebBrowser from the DJ project. In Revolucion Library I used latter. It’s an SWT-based implementation of web browser component and under Windows it uses Internet Explorer or Mozilla and Mozilla on other platforms. Features that I liked – you can call JavaScript function in current page from Java, and can send commands from html page to Java application. And it works pretty good.

So I made a simple html page with chromeless Youtube player and, among few others, it contains following JavaScript functions:


function onYouTubePlayerReady(playerId) {
          ytplayer = document.getElementById("myytplayer");
  ...
          sendCommand("loaded");
        }

function loadNewVideo(id, startSeconds) {
          if (ytplayer) {
            ytplayer.loadVideoById(id, parseInt(startSeconds));
          }
        }

function closePlayer() {
            stop();
            clearVideo();
          	sendCommand('close');
        }
function sendCommand(command) {
          var s = 'command://' + encodeURIComponent(command);
          for(var i=1; i<arguments.length; s+='&'+encodeURIComponent(arguments[i++]));
          window.location = s;
        }

Also I written a YouTube player component:


 public class YouTubePlayer extends JPanel {

 private JWebBrowser webBrowser;
 private String videoId;

 public YouTubePlayer(String videoId) {
 	this.videoId = videoId;

 	init();
 }

 private void init() {
 	webBrowser = new JWebBrowser();
 	webBrowser.setBarsVisible(false);
 	webBrowser.setButtonBarVisible(false);
 	webBrowser.setLocationBarVisible(false);
 	webBrowser.setMenuBarVisible(false);
 	webBrowser.setStatusBarVisible(false);
 	webBrowser.setBackground(Color.black);
 	webBrowser.getNativeComponent().setBackground(Color.black);
 	webBrowser.setFocusable(false);

 	webBrowser.setHTMLContent(generateHtmlPlayer());

 	webBrowser.addWebBrowserListener(new WebBrowserAdapter() {
 		@Override
 		public void commandReceived(WebBrowserEvent e, String command, String[] args) {
 			if (command.equals("close"))
 				firePropertyChange("action", null, "close");
 			else if (command.equals("loaded"))
 				webBrowser.executeJavascript("loadNewVideo(\"" + videoId + "\", \"0\")");
 		}
 	});

 	setBackground(Color.black);
 	setLayout(new BorderLayout());

 	add(webBrowser, BorderLayout.CENTER);
 }

 private String generateHtmlPlayer() {
 	String html = null;
 	try {
 		html = FileUtils.readFileToString(new File(getClass().getResource("resources/player_html.html").toURI()));
 	}
 	catch (Exception e) {}

 	return html;
 }
}

Explanation:

When the “player_html.html” page is opened in the browser and then Youtube player is loaded it will invoke the onYouTubePlayerReady function and it will send command to my YouTubePlayer component. WebBrowserListener receives the command and using the executeJavascript method calls the loadNewVideo function with videoId as a parameter. VideoId is a part of video url after “/v/” that you might remember from above :) When user clicks “close” button in the html page, closePlayer() function is called and command sent to application.

So, this is it. All in all, this is not the best solution, you must include SWT jar with your application, but it works for now.

I’m desperately waiting for JWebPane …

Added day later:

I forgot to mention WebKit4Java by Genuitec which is currently available for SWT, but there is also going to be a Swing version.

P.S. My english isn’t excellent so I’m sorry for grammatical and other mistakes I made.

About these ads

19 comments on “How It’s Made: Youtube player in Java

  1. cebollino says:

    I was desperate trying to load multimedia content into my java app, as u said JMC crashes from time to time.

    I didn’t know about the existence of DJProyect. Calling JavaScript from Java is the key that i was looking for. Very nice idea. That solution brings me life.

    Thanks for sharing! super-well explained :)

  2. [...] tricks he learnt. He has two posts, one about the cover gallery he created , and the other about creating a Java-based YouTube video player [...]

  3. James says:

    i try it and get a error(null, it need a object)

    i write a sample like this:
    **********************************

    function helloWorld() {
    alert(“helloWorld”);
    }

    *************************

    webBrowser.executeJavascript(“helloWorld()”);

    but get error(null, it need a object) again, can you tell me why? thx.

    • Željko says:

      I’m not really sure why it doesn’t work … Try the Javascript Execution example from here; if it works than there is some mistake in your code.

  4. James says:

    thx. i Successed :)

    how to disable(no visible) right Scroll ?

  5. James says:

    forget to tell you .
    i don’t use that html page,i use this html and js on my code :)

    I hope useful for you (it is also easy )

    http://www.longtailvideo.com/support/jw-player-setup-wizard?example=1

    final , thx again :>

  6. James says:

    i use it in the js code…Orz
    document.body.style.overflow=’hidden';

    sorry for bother you so many times ><

  7. NSJ says:

    how to get youtube information like totalbytes and set it to swing component (like JLabel text)?

    i had try this method:

    public Object executeJavascriptWithResult(String javascript)

    like as
    System.out.println(webBrowser.executeJavascriptWithResult(“getBytes()”));

    and the getBytes() method in js code will return a value.

    but always get error. (null)

    thank.

    • Željko says:

      I think that executeJavascriptWithResult(…) is not intended for calling javascript function by name. So instead of “getBytes()” you should write something like “return ytplayer.getBytes()”.
      If that doesn’t work, ask the same on the DJProject forum.

  8. Your blog is very interresting for me, i will come back here..

  9. ben says:

    i couldnt woork it out with YOutube Api
    to search and get video …
    can you give me instructtion ..
    i really need this for my assignment

    behrangbina@hotmail.com

  10. Ject says:

    Wow. this is exactly what i’ve been looking for (youtube player in java). Im new to html programming though and i cant get my player_html.html to load the video (player comes up but no video loads). do you think you could post or send me the full text of the html file you used?

    sorry, i know its kinda alot to ask but ive been trying to get this to work for a really long time now and ive kind of given up :(

  11. Ject says:

    hmm… I tried that and it didn’t work. Then I tried just saving the page to my computer and when I opened it, it had the exact same problem my webpage is. I get the feeling im doing something wrong.

  12. Ject says:

    Ok. I figured out the problem I was having and I thought I’d post this just for anyone else who may come across this same problem. The locally saved copy does not work by default when opened directly. If you use the method named above [setHtmlContent()] it will load the player and video correctly (as opposed to just a black player with the YouTube logo). This may seem like common sense to some (and im sorry if this insults your intelligence) but it was news to me so I figured it might be helpful to anyone who comes across this thread.

  13. shay says:

    can u share the complete html file ?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s