In preparation for an upcoming project I was looking at the youtube API for playing videos. The javascript API is actually really simple. However the code inside of my erb/haml files looked ugly because of the inline javascript.
I implemented a few basic features which are accessed via helper methods and wrote some crummy javascript (to be improved later) to provide access to the youtube API. You can check out the source if you like. Specifically, take a look at example.rb.
To start off you include youtube-helper.js and swfobject.js in your page. I was going to combine them, but decided to allow you to update swfobject as needed. The only function used is embedSWF. Inside your erb/haml use yt_player to display the youtube player. There are several variations:
# Will give a chromefull player with video ID
yt_player :video_id => "video_id"
# Chromeless video player with given video ID
yt_player :chromeless, :video_id => "video_id"The chromeless version does not need a video_id specified at the time and can be set using cueVideoById, which is documented in the youtube API.
There are a few more custom helpers which make it really simple to get something up and running:
yt_play_btn allows you to specify html which defaults to “play” and wraps it in a span tag which plays the video on click.yt_pause_btn allows you to specify html which defaults to “pause” and wraps it in a span tag which pauses the video on click.yt_register_state_callback allows you to specify a javascript function which will get called and passed a state value when the video state changes. You define the javascript function yourself.Other than that the youtube API is simple enough that you can use custom javascript to interact with it by using yt_get_player.
onload which can’t be redefined by custom code.As the next project is worked on I will be cleaning up the code to allow for as little inline javascript as possible. I am trying to decide if it’s worth it to build a couple of library independent widgets, or use someone else’s, such as sliders and number boxes, to implement things like a volume slider/progress bar and leave it up to css styling to make it pretty.
youtube-helper saves you time in setting up the player. It has a simple, nice, and clean interface, with many options which can be specified to the swfobject. Depending on how useful it is we may update it to support a variety of players such as Vimeo.