Warning: HTML preview using PygmentsRenderer failed (TypeError: function() takes at least 2 arguments (0 given))

source: trunk/fl5/doc/publishers/javascriptapi.rst @ 1344

Revision 1344, 16.0 KB checked in by pablo, 3 years ago (diff)

Updates to the documentation

Line 
1.. _javascriptapi:
2
3Player API
4==========
5
6The 5.3 player introduces a new, shorthand javascript API for interacting with your website. This API abstracts any differences between Flash and HTML5; any code you write will work with both technologies.
7
8For versions 5.2 and below, the player used the 4.x JavaScript API.  A reference for that API can be found on the `player support site <http://www.longtailvideo.com/support/jw-player/jw-player-for-flash-v4/12209/javascript-api-reference>`_.
9
10
11Getting started
12---------------
13
14First, you'll need to upload the API library (*jwplayer.js*) to your web server.  We recommend putting it, along with *player.swf*, in a folder called **jwplayer** in the root of your site.  Once it's on your web server, add this bit of code to your HTML pages, in the *<head>* of your page:
15
16.. code-block:: html
17
18        <head>
19                <script type="text/javascript" src="/jwplayer/jwplayer.js"></script>
20        </head>
21
22To get a sense of the possibilities of what you can do with the API, here's a quick example that showcases how to control the player from the page:
23
24.. code-block:: html
25   
26    <div id="container">Loading the player ...</div>
27   
28    <script type="text/javascript">
29        jwplayer("container").setup({
30            flashplayer: "/jwplayer/player.swf",
31            file: "/uploads/video.mp4",
32            height: 270,
33            width: 480
34        });
35    </script>
36   
37    <ul>
38        <li onclick="jwplayer().play()">Start the player</li>
39        <li onclick="alert(jwplayer().getPosition())">Get current position</li>
40    </ul>
41
42Of course it's also possible to have the player manipulate the page. Here's a second example, using the  :ref:`event block <embed_events>` of the JW Player embedder:
43
44.. code-block:: html
45   
46    <div id="container">Loading the player ...</div>
47   
48    <script type="text/javascript">
49        jwplayer("container").setup({
50            flashplayer: "/jwplayer/player.swf",
51            file: "/uploads/video.mp4",
52            height: 270,
53            width: 480,
54            events: {
55                onComplete: function() {
56                    document.getElementById("status").innerHTML("That's all folks!");
57                }
58            }
59        });
60    </script>
61   
62    <p id="status"></p>
63
64The following sections give a detailed description of the JW Player API, describing how to:
65
66* Select a player.
67* Get variables from a player.
68* Call functions on a player.
69* Listen to events from a player.
70
71Embedding with SWFObject
72++++++++++++++++++++++++
73
74If you embed the player using SWFObject, rather than the built-in *setup()* function, you can still use the JavaScript API, although you'll need to wait for Flash to be loaded on the page before interacting with the API.  SWFObject 2.2 includes a callback function (in this example, named **flashLoaded**) which is executed when SWFObject has finished embedding Flash into the page.  Make sure you wait until this function is called before making any calls to the API.
75
76Here's a simple example of using the `SWFObject callback <http://code.google.com/p/swfobject/wiki/api>`_:
77
78.. code-block:: javascript
79
80        var flashvars = { file:"/videos/video.mp4" };
81        var params = { allowfullscreen:"true", allowscriptaccess:"always" };
82        var attributes = { id:"player", name:"player" };
83       
84        swfobject.embedSWF("/jwplayer/player.swf", "container", 320, 240, "9.0.115", "false",
85            flashvars, params, attributes, flashLoaded);
86
87        function flashLoaded(e) {
88                // e.ref is a reference to the Flash object.  We'll pass it to jwplayer() so the API knows where the player is.
89         
90            // Add event listeners
91            jwplayer(e.ref).onReady(function() { alert("Player is ready"); });
92            jwplayer(e.ref).onPlay(function() { alert("Player is playing"); });
93
94            // Interact with the player
95            jwplayer(e.ref).play();
96        }
97
98Embedding with an <object> or <embed> tag
99+++++++++++++++++++++++++++++++++++++++++
100
101If you embed the player directly using an *<object>* or *<embed>* tag, simply pass your tag's id to the API when referencing the player:
102
103.. code-block:: html
104
105        <embed
106          id="player"
107          name="player"
108          src="/jwplayer/player.swf"
109          width="320"
110          height="240"
111          allowscriptaccess="always"
112          allowfullscreen="true"
113          flashvars="file=/videos/video.mp4"
114        />
115       
116        <script type="text/javascript">
117            jwplayer("player").onReady(function() { alert("Player is ready"); });
118            jwplayer("player").onPlay(function() { alert("Player is playing"); });
119            jwplayer("player").play();
120        </script>
121
122Selecting
123---------
124
125The first thing you need to do when attempting to interact with a JW Player, is to get a reference to it. The easiest way, probably sufficient for 95% of all use cases is this:
126
127.. code-block:: javascript
128
129    // Start the player on this page
130    jwplayer().play();
131
132
133Only when you have multiple players on a page, you need to be more specific on which player you want to interact with. In that case, there are three ways to select a player:
134
135* With the *id* of the element you :ref:`instantiated <embedding>` the player over:
136   
137    .. code-block:: javascript
138   
139        jwplayer("container").play();
140
141* With the actual DOM element itself:
142   
143    .. code-block:: javascript
144   
145        var element = document.getElementById("container");
146        jwplayer(element).play();
147
148* With the index in the list of players on the page (in order of loading):
149   
150    .. code-block:: javascript
151     
152        jwplayer(2).play();
153   
154    .. note::
155   
156        The selector *jwplayer(0)* is actually the same as *jwplayer()*.
157
158
159
160Variables
161---------
162
163Here is a list of all the variables that can be retrieved from the player:
164
165.. describe:: getBuffer()
166
167    Returns the current PlaylistItem's filled buffer, as a **percentage** (0 to 100) of the total video's length.
168   
169.. describe:: getFullscreen()
170
171    Returns the player's current **fullscreen** state, as a boolean (*true* when fullscreen).
172
173.. describe:: getMetadata()
174
175    Returns the current PlaylistItem's **metadata**, as a javascript object. This object contains arbitrary key:value parameters, depending upon the type of player, media file and streaming provider that is used. Common metadata keys are *width*, *duration* or *videoframerate*.
176
177.. describe:: getMute()
178
179    Returns the player's current audio muting state, as a boolean (*true* when there's no sound).
180
181.. describe:: getPlaylist()
182
183    Returns the player's entire **playlist**, as an array of PlaylistItem objects. Here's an example playlist, with three items:
184   
185    .. code-block:: javascript
186   
187        [
188            { duration: 32, file: "/uploads/video.mp4", image: "/uploads/video.jpg" },
189            { title: "cool video", file: "/uploads/bbb.mp4" },
190            { duration: 542, file: "/uploads/ed.mp4", start: 129 }
191        ]
192
193.. describe:: getPlaylistItem(*index*):
194
195    Returns the playlist **item** at the specified *index*. If the *index* is not specified, the currently playing playlistItem is returned. The **item**  that is returned is an object with key:value properties (e.g. *file*, *duration* and *title*). Example:
196   
197    .. code-block:: javascript
198   
199        { duration: 32, file: "/uploads/video.mp4", image: "/uploads/video.jpg" }
200
201.. describe:: getWidth()
202
203    Returns the player's current **width**, in pixels.
204
205.. describe:: getHeight()
206
207    Returns the player's current **height**, in pixels.
208
209.. describe:: getState()
210
211    Returns the player's current playback state. It can have the following values:
212   
213    * **BUFFERING**: user pressed *play*, but sufficient data has to be loaded first (no movement).
214    * **PLAYING**: the video is playing (movement).
215    * **PAUSED**: user paused the video (no movement).
216    * **IDLE**: either the user stopped the video or the video has ended (no movement).
217
218.. describe:: getPosition()
219
220    Returns the current playback **position** in seconds, as a number.
221
222.. describe:: getDuration()
223
224    Returns the currently playing PlaylistItem's duration in seconds, as a number.
225
226.. describe:: getVolume()
227
228    Returns the current playback volume percentage, as a number (0 to 100).
229
230
231
232Functions
233---------
234
235Here is a list of all functions that can be called on the player:
236
237.. describe:: setFullscreen(state)
238
239    Change the player's fullscreen mode. Parameters:
240   
241    * **state**:Boolean (*undefined*): If state is undefined, perform a fullscreen toggle. Otherwise, set the player's fullscreen mode to fullscreen if true, and return to normal screen mode if false.
242
243.. describe:: setMute(state)
244
245    Change the player's mute state (no sound). Parameters:
246
247    * **state**:Boolean (undefined): If *state* is undefined, perform a muting toggle. Otherwise, mute the player if true, and unmute if false.
248
249.. describe:: load(playlist)
250
251    Loads a new playlist into the player. The **playlist** parameter is required and can take a number of forms:
252   
253    * *Array*: If an array of PlaylistItem objects is passed, load an entire playlist into the player. Example:
254   
255        .. code-block:: javascript
256       
257            [
258                { duration: 32, file: "/uploads/video.mp4", image: "/uploads/video.jpg" },
259                { title: "cool video", file: "/uploads/bbb.mp4" },
260                { duration: 542, file: "/uploads/ed.mp4", start: 129 }
261            ]
262
263    * *Object*: If a PlaylistItem is passed, load it as a single item into the player. Example:
264   
265        .. code-block:: javascript
266       
267            { duration: 32, file: "/uploads/video.mp4", image: "/uploads/video.jpg" },
268       
269    * *String*: Can be an XML playlist, or the link to a single media item (e.g. an MP4 video).
270
271.. describe:: playlistItem(index)
272
273    Jumps to the playlist item at the specified index. Parameters:
274   
275    * **index**:Number: zero-based index into the playlist array (i.e. playlistItem(0) jumps to the first item in the playlist).
276
277.. describe:: playlistNext()
278
279    Jumps to the next playlist item. If the current playlist item is the last one, the player jumps to the first.
280
281.. describe:: playlistPrev()
282
283    Jumps to the previous playlist item. If the current playlist item is the first one, the player jumps to the last.
284
285.. describe:: resize(width, height)
286
287    Resizes the player to the specified dimensions. Parameters:
288   
289    * **width**:Number: the new overall width of the player.
290    * **height**:Number: the new overall height of the player.
291   
292    .. note::
293   
294        If a controlbar or playlist is displayed next to the video, the actual video is of course smaller than the overall player.
295
296.. describe:: play(state)
297
298    Toggles playback of the player. Parameters:
299   
300    * **state**:Boolean (undefined): if set *true* the player will start playing. If set *false* the player will pause. If not set, the player will toggle playback.
301
302
303.. describe:: pause(state)
304
305    Toggles playback of the player. Parameters:
306   
307    * **state**:Boolean (undefined): if set *true* the player will pause playback. If set *false* the player will play. If not set, the player will toggle playback.
308   
309.. describe:: stop()
310
311    Stops the player and unloads the currently playing media file from memory.
312
313.. describe:: seek(position)
314
315    Jump to the specified position within the currently playing item. Parameters:
316
317    * **position**:Number: Requested position in seconds.
318
319.. describe:: setVolume(volume)
320
321    Sets the player's audio volume. Parameters:
322   
323    * **volume**:Number: The new volume percentage; *0* and *100*.
324
325
326
327Events
328------
329
330Here is a list of all events the player supports. In javascript, you can listen to events by assigning a function to it. Your function should take one argument (the event that is fired). Here is a code example, with some javascript that listens to changes in the volume:
331
332.. code-block:: javascript
333   
334    jwplayer("container").onVolume(
335        function(event) {
336            alert("the new volume is: "+event.volume);
337        }
338    );
339
340Note that our :ref:`official embed method <embedding>` contains a shortcut for assigning event listeners, directly in the embed code:
341
342.. code-block:: html
343   
344    <div id="container">Loading the player ...</div>
345   
346    <script type="text/javascript">
347        jwplayer("container").setup({
348            flashplayer: "/jwplayer/player.swf",
349            file: "/uploads/video.mp4",
350            height: 270,
351            width: 480,
352            events: {
353                onVolume: function(event) {
354                    alert("the new volume is: "+event.volume);
355                }
356            }
357        });
358    </script>
359
360
361And here's the full event list:
362
363.. describe:: onBufferChange(callback)
364
365    Fired when the currently playing item loads additional data into its buffer. Event attributes:
366
367    * **percent**: Number: Percentage (between 0 and 100); number of seconds buffered / duration in seconds.
368
369.. describe:: onBufferFull(callback)
370
371    Fired when the player's buffer has exceeded the player's bufferlength property (default: 1 second). No attributes.
372
373.. describe:: onError(callback)
374
375    Fired when an error has occurred in the player. Event attributes:
376
377    * **message**: String: The reason for the error.
378
379.. describe:: onFullscreen(callback)
380
381    Fired when the player's fullscreen mode changes. Event attributes:
382   
383    * fullscreen: boolean. New fullscreen state.
384
385.. describe:: onMetadata(callback)
386
387    Fired when new metadata has been discovered in the player. Event attributes:
388
389    **data**: Object: dictionary object containing the new metadata.
390
391.. describe:: onMute(callback)
392
393    Fired when the player has gone into or out of the mute state. Event attributes:
394
395    * **mute**: Boolean: New mute state.
396
397.. describe:: onPlaylist(callback)
398
399    Fired when a new playlist has been loaded into the player. Event attributes:
400   
401    * **playlist**: Array: The new playlist; an array of PlaylistItem objects.
402
403.. describe:: onPlaylistItem(callback)
404
405    Fired when the player is playing a new media item. Event attributes:
406
407    * **index** Number: Zero-based index into the playlist array (e.g. 0 is the first item).
408
409.. describe:: onReady(callback)
410
411    Fired when the player has initialized and is ready for playback. No attributes.
412
413.. describe:: onResize(callback)
414
415    Fired when the player's dimensions have changed (the player is resizing or switching fullscreen). Event attributes:
416
417    * **width**: Number: The new width of the player.
418    * **height**: Number: The new height of the player.
419
420.. describe:: onPlay(callback)
421
422    Fired when the player enters the *PLAYING* state. Event attributes:
423
424    * **oldstate**: String: the state the player moved from. Can be *PAUSED* or *BUFFERING*.
425
426.. describe:: onPause(callback)
427
428    Fired when the player enters the PAUSED state. Event attributes:
429
430    * **oldstate**: String: the state the player moved from. Can be *PLAYING* or *BUFFERING*.
431
432.. describe:: onBuffer(callback)
433
434    Fired when the player enters the BUFFERING state. Event attributes:
435
436    * **oldstate**: String: the state the player moved from. Can be *PLAYING*, *PAUSED* or *IDLE*.
437
438.. describe:: onIdle(callback)
439
440    Fired when the player enters the IDLE state. Event attributes:
441
442    * **oldstate**: String: the state the player moved from. Can be *PLAYING*, *PAUSED* or *BUFFERING*.
443
444.. describe:: onComplete(callback)
445
446    Fired when the player has finished playing the current media. No event attributes.
447
448.. describe:: onPosition(callback)
449
450    When the player is playing, fired as the playback position gets updated. This happens with a resolution of 0.1 second, so there's a lot of events! Event attributes:
451
452    * **duration**: Number: Duration of the current item in seconds.
453    * **offset**: Number: When playing streaming media, this value contains the last unbuffered seek offset.
454    * **position**: Number: Playback position in seconds.
455
456.. describe:: onVolume(callback)
457
458    Fired when the player's volume changes. Event attributes:
459
460    * **volume**: Number: The new volume percentage (0 to 100).
461
462
463
464Chaining
465--------
466
467Note that every API call to a JW Player in turn returns the player instance. This makes it possible to chain API calls  (like with `jQuery <http://jquery.net>`_):
468
469.. code-block:: javascript
470
471    jwplayer().setVolume(50).onComplete(function(){ alert("done!"); }).play();
472
473
Note: See TracBrowser for help on using the repository browser.