42
Copyright 2010 TokBox, Inc. All rights reserved. TokBox is a registered trademark and OpenTok is a trademark of TokBox, Inc. Tutorials and Sample Code

Open tok api_tutorials

Embed Size (px)

Citation preview

Page 1: Open tok api_tutorials

Copyright 2010 TokBox, Inc. All rights reserved. TokBox is a registered trademark and OpenTok is a trademark of TokBox, Inc.

 

 

   

Tutorials  and  Sample  Code  

 

 

 

 

 

   

Page 2: Open tok api_tutorials

JavaScript API: Tutorials and Sample Code

Basic Functionality

Hello World

Shows you how to connect to a session, publish a stream from your webcam, and view other audio-video streams in the session … all in just a few lines of code.

Basic tutorial

Expands on the Hello World tutorial, showing how to position OpenTok videos in the HTML DOM.

Debugging OpenTok applications

Shows you techniques for debugging an application that uses the OpenTok JavaScript library.

Advanced Tutorials

Pre-publish set-up

Shows how to select and test cameras and microphones prior to publishing a stream to a session.

Moderation and signaling

Shows how to moderate participants in an OpenTok session, and how to have a participant send a signalto all other participants.

Resizing videos

Shows how you can control the size of the OpenTok video display, just as you would any other HTMLelement.

Audio-only and video only

Shows how to publish streams and subscribe to streams in audio-only and video-only mode.

Passing user information

Shows how to set and retrieve metadata for each client connecting to a session.

Recording stand-alone archives

OpenTok JavaScript API Tutorials and Sample Code 2

Copyright 2012 TokBox, Inc. All rights reserved. 6/13/2012

Page 3: Open tok api_tutorials

Shows how to record an audio-video stream outside of an OpenTok session and then play it back in asession.

OpenTok JavaScript API Tutorials and Sample Code 3

Copyright 2012 TokBox, Inc. All rights reserved. 6/13/2012

Page 4: Open tok api_tutorials

JavaScript Tutorial — Hello World Tutorial

This tutorial shows how to connect to an OpenTokTM session, display any existing streams and publish avideo stream to the session. Although this is not a traditional "hello world" sample, it does show the mostbasic application to use the most basic OpenTok functionality.

Testing the tutorial online

To run the tutorial at the top of this page:

1. Make sure that you have a webcam connected to your computer and configured to run.

2. In the example at the top of this page, if the Flash Player Settings dialog is displayed, click theAllow button. This grants the application access to your camera and microphone.

The example now connects to a sample OpenTok session. It displays any other video streams inthe session (if there are any), and it displays and publishes your video to the session.

3. Mute the speaker on your computer. (For this test app, this will prevent audio feedback.)

4. Copy the URL for this page into the Clipboard.

5. Open a new browser window, and have it open to the copied URL.

For test purposes, you can view the page in the new browser window on your computer. Or youcan open it on another computer (as would happen in a real session.)

The new page now connects to the session. Upon connection the video stream from the otherpage is displayed on the page and the new published video stream appears on both pages.

You can wave to the camera and say "hello world."

Understanding the code

This application shows the simplest example of connecting to an OpenTok session, displaying videostreams existing in the session, and publishing a video stream to a session.

We assume you know how to create HTML Web pages and have a basic understanding of JavaScript andthe HTML Document Object Model. If you are not comfortable with those technologies, then you shouldconsider using the TokBox Embed option instead.

Adding the OpenTok JavaScript library

To add the OpenTok JavaScript library, the <head> section of the webpage includes the following line:

<script src="http://staging.tokbox.com/v0.91/js/TB.min.js" ></script>

This one script includes the entire OpenTok JavaScript library. The src URL will change with future

OpenTok JavaScript API Tutorials and Sample Code 4

Copyright 2012 TokBox, Inc. All rights reserved. 6/13/2012

Page 5: Open tok api_tutorials

versions of the OpenTok API. However, TokBoxTM will maintain this version at the original URL.

Connecting to an OpenTok session

The first step in using an OpenTok session is to create and initialize a Session object. The Session object isdefined in the OpenTok JavaScript library. You initialize a Session object by calling the TB.initSession()method with the session ID pertaining to the OpenTok session. In this case, it is the ID for the samplesession used for this demo:

var session = TB.initSession("1sdemo00855f8290f8efa648d9347d718f7e06fd");

The TB object and Session object are defined in the OpenTok JavaScript library. (See the OpenTokJavaScript API reference for details.)

Once the initialization is complete, you can connect to the session by calling the connect() method of theSession object. The connect() method takes two arguments: the API key and the token string:

session.connect(1127, "devtoken");

The API key identifies you as an OpenTok developer. (In this case, it is a sample API key used for thetutorial.) The token string defines a user. The Basic Tutorial describes these in more detail.

Before calling the connect() method of the Session object, the code adds event listeners that enable theOpenTok controller to send events to JavaScript functions:

session.addEventListener("sessionConnected", sessionConnectedHandler);session.addEventListener("streamCreated", streamCreatedHandler);

The sessionConnectedHandler() function calls a function that subscribes to the existing streams in thesession, and it publishes your camera's video to the session:

function sessionConnectedHandler (event) { subscribeToStreams(event.streams); session.publish();}

function subscribeToStreams(streams) { for (i = 0; i < streams.length; i++) { var stream = streams[i]; if (stream.connection.connectionId != session.connection.connectionId) { session.subscribe(stream); } }}

The publish() method of a Session object lets you publish your webcam's audio-video stream to thesession.

The streamCreatedHandler() function processes streams that are added to a session (after you initiallyconnect):

function streamCreatedHandler(event) { subscribeToStreams(event.streams);}

OpenTok JavaScript API Tutorials and Sample Code 5

Copyright 2012 TokBox, Inc. All rights reserved. 6/13/2012

Page 6: Open tok api_tutorials

Both the sessionConnected event and the streamCreated event objects contain a streams property, which isan array of streams. The subscribeToStreams() function calls the subscribe() method of the OpenTokSession object to subscribe to each stream.

Note that the subscribeToStreams() function checks to make sure that a stream does not correspond tothe one you are publishing (as determined by the session.connection.connectionId property).

When the code calls publish() and subscribe(), this simple sample app simply adds video streams in newDIV elements appended to the HTML body. However, you can (and usually will) want to assign streams toHTML elements you define. The publish() and subscribe() methods each take an optionalreplaceElementId parameter. To see how this works, look at the Basic Tutorial.

Testing the code on your own computer

You can download the source code and test it on your own computer:

1. Click the Download the source code link at the top of this page (just beneath the example).

2. Extract the ZIP file you download, and open the helloworld.html file in a web browser.

Flash Player Settings for local testing:

If the web page asks you to set the Flash Player Settings, or if you do not see a display of your camera inthe page, do the following:

1. Open this link in a new browser window:http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04.html.

The Flash Player Global Security Settings panel is displayed.

2. In the Alway trust files in these locations list click the Edit locations link and select Add location.

3. Click Browse for folder, navigate to the folder that contains the files you downloaded, and thenclick the Open button.

4. Click the Always Allow button.

This grants the HTML pages in the folder you selected to communicate with Flash contentserved by tokbox.com. (It also grants this communication from this folder to other servers, so becareful to select a specific folder.)

5. Reload the local version of the HTML file in your web browser.

Next steps

Now that you have looked at this simple example, go ahead and read the Basic Tutorial. Then look at theother tutorials to learn more of the OpenTok functionality.

You may also want to look at the OpenTok documentation.

OpenTok JavaScript API Tutorials and Sample Code 6

Copyright 2012 TokBox, Inc. All rights reserved. 6/13/2012

Page 7: Open tok api_tutorials

OpenTok JavaScript API Tutorials and Sample Code 7

Copyright 2012 TokBox, Inc. All rights reserved. 6/13/2012

Page 8: Open tok api_tutorials

JavaScript Tutorial — Basic Tutorial

This tutorial shows how to connect to an OpenTokTM session, display any existing streams andpublish a video stream to the session.

Testing the tutorial online

To run the tutorial at the top of this page:

1. Make sure that you have a webcam connected to your computer and configured to run.

2. Click the Publish link, at the top of the page.

If the Flash Player Settings dialog is displayed, click the Allow button. This grants theapplication access to your camera and microphone.

You are now publishing a video stream to the session, and the video stream is displayed onthe page.

3. Copy the URL for this page into the Clipboard.

4. Open a new browser window, and have it open to the copied URL.

For test purposes, you can the new browser window on your computer. Or you can open iton another computer (as would happen in a real session.)

5. Click the Connect link, at the top of the page (in the new browser window).

The new page now connects to the session. Upon connection the video stream from theother page is displayed on the page.

6. Click the Publish link, at the top of the page.

You are now publishing a new video stream to the session. This new video stream isdisplayed on the other browser page.

7. Click the Unpublish link.

The page removes the video from the session. It is also removed from all pages.

8. Click the Disconnect link.

This disconnects you from the session (and removes all videos from the page).

Understanding the code

We assume you know how to create HTML Web pages and have a basic understanding of JavaScript

OpenTok JavaScript API Tutorials and Sample Code 8

Copyright 2012 TokBox, Inc. All rights reserved. 6/13/2012

Page 9: Open tok api_tutorials

and the HTML Document Object Model. If you are not comfortable with those technologies, then youshould consider using the TokBox Embed option instead.

Adding the OpenTok JavaScript library

To add the OpenTok JavaScript library, the <head> section of the webpage includes the followingline:

<script src="http://staging.tokbox.com/v0.91/js/TB.min.js" ></script>

This one script includes the entire OpenTok JavaScript library. The src URL will change with futureversions of the OpenTok API. However, TokBoxTM will maintain this version at the original URL.

Connecting to an OpenTok session

The top of the code defines these values, which identify the developer, the OpenTok session and theuser:

<script type="text/javascript">

var apiKey = 1127; // OpenTok sample code key. Replace with your own API key.var sessionId = '153975e9d3ecce1d11baddd2c9d8d3c9d147df18'; // Replace with your session ID.var token = 'devtoken'; // Should not be hard-coded. // Add to the page using the OpenTok server-side libraries.

These variables define the following values:

The API key identifies you as a developer registered to use the OpenTok API. You will obtainan API key from TokBox when you register to use the OpenTok API (at the Get your API keypage). While testing out the basic tutorial application, you can use the sample code API key(1127). When you develop your own application, you will use the API key assigned to you.

The session ID is a unique identifier for your OpenTok video chat session. For this basic tutorialapplication, you can use the provided session ID. For your own application, you will obtainyour own session ID from TokBox.

The token string identifies a user. While using a test version of an application (such as thisbasic tutorial), you can use the "devtoken" token string. When you deploy your application,you will use the OpenTok server-side libraries to obtain a unique token string for eachparticipant in the session. This token string is used to validate a participant.

The first step in using an OpenTok session is to create and initialize a Session object. The Sessionobject is defined in the OpenTok JavaScript library. You initialize a Session object by calling theTB.initSession() method with the session ID pertaining to the OpenTok session:

session = TB.initSession(sessionId);

The TB object and Session object are defined in the OpenTok JavaScript library.

OpenTok JavaScript API Tutorials and Sample Code 9

Copyright 2012 TokBox, Inc. All rights reserved. 6/13/2012

Page 10: Open tok api_tutorials

Once the initialization is complete, you can connect to the session by calling the connect() method ofthe Session object. The connect() method takes two arguments: the API key and the token string:

var session;session = TB.initSession(sessionId);

function connect() { session.connect(apiKey, token);}

Note: The objects, methods, properties, and events in the OpenTok JavaScript API are described inthe OpenTok JavaScript API reference.

In the basic tutorial application, the Connect link in the HTML page calls the connect() function(which calls the connect() method of the Session object).

Before calling the connect() method of the Session object, the code adds event listeners that enablethe OpenTok controller to send events to JavaScript functions:

var session;var publisher;var subscribers = {};

// TB.setLogLevel(TB.DEBUG);if (TB.checkSystemRequirements() != TB.HAS_REQUIREMENTS) { alert('Minimum System Requirements not met!');}

TB.addEventListener('exception', exceptionHandler);session = TB.initSession(sessionId);

session.addEventListener('sessionConnected', sessionConnectedHandler);session.addEventListener('sessionDisconnected', sessionDisconnectedHandler);session.addEventListener('connectionCreated', connectionCreatedHandler);session.addEventListener('connectionDestroyed', connectionDestroyedHandler);session.addEventListener('streamCreated', streamCreatedHandler);session.addEventListener('streamDestroyed', streamDestroyedHandler);

function connect() { session.connect(apiKey, token);}

Objects in the OpenTok JavaScript library uses the addEventListener() method to register eventlistener function to events. Event types are identified with strings. For example, the Session objectdispatches a sessionConnected event when the OpenTok controller successfully connects to theOpenTok session. You can add the listeners for all the events you are interested in subscribing to.

The sections that follow will describe the event listeners in this code.

Publishing an audio-video stream to an OpenTok session

The TB.initPublisher() method lets you instantiate a Publisher object, which displays the video fromyour webcam, and add it to the HTML DOM. The publish() method of a Session object lets youpublish your webcam's audio-video stream to the session:

var div = document.createElement('div');

OpenTok JavaScript API Tutorials and Sample Code 10

Copyright 2012 TokBox, Inc. All rights reserved. 6/13/2012

Page 11: Open tok api_tutorials

div.setAttribute('id', 'publisher');document.body.appendChild(div);publisher = TB.initPublisher(apiKey, 'publisher');session.publish(publisher);publisher.addEventListener('settingsButtonClick', showSettings);

The TB.initPublisher() takes the ID of an HTML element as the second parameter (which in thiscase is a div element with the ID "publisher"). The method replaces with a video box (publisher)containing audio and video.

The TB.initPublisher() method also returns a Publisher object, which can be used to performoperations (like unpublish the stream if you want to). In this case we keep track of the publisherobject so we can use it to unpublish or perform custom clean up later on.

The unpublish() method of the Session object removes your published video stream from thesession. It also removes the display of the video from the page. The Unpublish link on the page callsthe unpublish() function:

if (publisher) { session.unpublish(publisher);}publisher = null;

Subscribing to streams

When users publish streams to an OpenTok session, the Session object dispatches aStreamConnected event. It also dispatches this event when you first connect to the session. The codein this tutorial registers the streamCreatedHandler() method as the event listener for thestreamCreated event:

function streamCreatedHandler(event) { for (var i = 0; i < event.streams.length; i++) { addStream(event.streams[i]); }}

The streamCreated event object is defined by the StreamEvent object in the OpenTok JavaScriptlibrary. The StreamEvent object includes a streams property, which is an array of Stream objectspertaining to the event. The code above loops through all the streams available and calls theaddStream() function:

function addStream(stream) { if (stream.connection.connectionId == session.connection.connectionId) { return; } var div = document.createElement('div'); var divId = stream.streamId; div.setAttribute('id', divId); document.body.appendChild(div); subscribers[stream.streamId] = session.subscribe(stream, divId);}

The addStream() function takes a stream object and subscribes to it. The code first creates an HTML

OpenTok JavaScript API Tutorials and Sample Code 11

Copyright 2012 TokBox, Inc. All rights reserved. 6/13/2012

Page 12: Open tok api_tutorials

div element which will be replaced by the subscriber UI component. The subscribe() method of theSession object takes two arguments: a Stream object and the HTML element. In the first line of thefunction above, the code checks to see if a Stream object references the stream we published. Wealso use the stream.streamid as the div ID, so we have an easy, mechanism to get unique IDs. In thiscase we also keep track of all Subscriber objects so we can use them for cleanup at some later pointin time.

The Session object dispatches a streamDestroyed event when a stream leaves a session. This mayhappen if a user disconnects or stops publishing a stream. The default behavior for this event is tounsubscribe from any Subscribers corresponding to the stream. (This default behavior was added inOpenTok v0.91.) You can cancel the default behavior by calling the preventDefault() method of thestreamDestroyed event object. If you cancel the default behavior, you can remove Subscriber objectsusing your own code by calling the unsubscribe() method of a Subscriber object. (The streamsproperty of the event is an array of Stream objects. The getSubscribersForStream() method of theSession object lists the Subscriber objects pertaining to a Stream.)

The Subscriber object is defined by the OpenTok JavaScript library. You created a Subscriber objectwhen you subscribed to each stream, using the subscribe() method of the Session objects. You cansubscribe to a stream multiple times (putting it in multiple places on the HTML page). However thistutorial only subscribes to each stream once.

Note also that the streamCreated and streamDestroyed events each include a streams property. Thesemay contain only one Stream object (when a single stream is added or removed from a session).

Disconnecting from the session

When the user clicks the Disconnect link on the page, the disconnect() function is called. This in turncalls the disconnect() method of the Session object. Disconnecting from a session is anasynchronous operation. When the session has disconnected, the Session object dispatches thesessionDisconnected event, which is handled by the the sessionDisconnected() function. Thisfunction simply changes the page to show the Connect link.

The default behavior of the sessionDisconnected event is to unsubscribe from any Subscriberscorresponding to the stream and remove the Publisher from the page. (This default behavior wasadded in OpenTok v0.91.) You can cancel the default behavior by calling the preventDefault()method of the sessionDisconnected event object. If you cancel the default behavior, you can removeSubscriber and Publisher objects using your own code. You can call the unsubscribe() method andthe unpublish() method of the Session object. (The Session object has a subscribers property and apublishers property, which are arrays of Subscriber and Publisher objects.)

The Session object also dispatches a sessionDisconnected event if a session connection is lostinadvertantly, as in the case of a lost network connection.

Handling errors and debugging

The TB object dispatches exception event when the application encounters an error event.

OpenTok JavaScript API Tutorials and Sample Code 12

Copyright 2012 TokBox, Inc. All rights reserved. 6/13/2012

Page 13: Open tok api_tutorials

The exceptionHandler() function is registered as the event listener for error events:

function exceptionHandler(event) { alert("Exception msg:" + event.message + "title: " + event.title + " code: " + event.code);}

However, the event handler for the exception event is commented out near the top of the code (inthe second line shown here):

// TB.setLogLevel(TB.DEBUG);// TB.addEventListener("exception", exceptionHandler);

You can uncomment the call to the addEventListener() method of the TB object to register the eventlistener. Or you can uncomment the first line to turn on the OpenTok logging feature. When you callTB.setLogLevel(TB.DEBUG), the OpenTok JavaScript library logs API actions to a debugger console,such as FireBug. Included in the logged messages are warnings, errors, and other useful information.If no debugger is connected, errors are displayed in JavaScript alert messages.

Note that the code also checks to see if the OpenTok API is supported on the client browser:

if (TB.checkSystemRequirements() != TB.HAS_REQUIREMENTS) { alert('Minimum System Requirements not met!');}

Testing the code on your own computer

See the instructions in the Hello World tutorial.

Creating a production version of an application

Once you are ready to show your app to the world, do the following:

1. Register your app with Tokbox. See the Launch page.

2. Use one of the OpenTok server-side libraries to obtain session IDs and unique token strings foreach user. Make sure that the API_URL constant in the library you use is set tohttps://api.opentok.com/hl. See the OpenTok server-side libraries documentation.

3. Load the OpenTok JavaScript library from the following URL: <scriptsrc="http://static.opentok.com/v0.91/js/TB.min.js"></script>.

For more information on testing and production versions of applications, see Testing and Production.

OpenTok JavaScript API Tutorials and Sample Code 13

Copyright 2012 TokBox, Inc. All rights reserved. 6/13/2012

Page 14: Open tok api_tutorials

JavaScript Tutorial — Debugging OpenTok appsThis tutorial describes effective means to debug an app that uses the OpenTok JavaScript library.

Logging to the console

You can configure your app to log messages to the developer console and to an element in the HTMLpage:

In JavaScript, call the TB.setLogLevel() method, passing in one of the following values:

TB.DEBUG — Fine-grained logging of all API actions.

TB.ERROR — Logging of errors only.

TB.INFO — Logging of warnings, errors, and other useful information, in addition to warningsand errors.

TB.NONE — API logging is disabled.

TB.WARN — Logging of warnings and errors.

To open the developer console:

In Google Chrome: on the View menu, select Developer > JavaScript Console.

In Firefox: install a debugger add-on. Firebug is a popular choice. It is available athttps://addons.mozilla.org/en-US/firefox/addon/firebug/. (Once you install Firebug, on theFirefox Tools menu, select Web Developer > Firebug > Open Firebug.)

In Safari: on the Develop menu, select Show Error Console.

In Internet Explorer 9: press the F12 key. In the F12 window, click the Console tab.

For example, the following code enables full logging to the console:

TB.setLogLevel(TB.DEBUG);

When you set the log level to TB.DEBUG, the console displays the following information:

[DEBUG] opentok: OpenTok JavaScript library[DEBUG] opentok: Release notes: http://staging.tokbox.com/opentok/api/tools/js/documentation/overview/releaseNotes.html[DEBUG] opentok: Known issues: http://staging.tokbox.com/opentok/api/tools/js/documentation/overview/releaseNotes.html#known

The OpenTok JavaScript library logs additional information. For example, if you connect to a session,the console displays the following (followed by the session ID):

OpenTok JavaScript API Tutorials and Sample Code 14

Copyright 2012 TokBox, Inc. All rights reserved. 6/13/2012

Page 15: Open tok api_tutorials

[DEBUG] opentok: TB.sessionConnected:

As you are developing, check the release notes and its list of known issues. The release notes keepyou up-to-date on new features. This list of known issues can let you know if the issue you areexperiencing is one that TokBox is aware of.

You can also see OpenTok console output by adding an HTML element with the id attribute set to"opentok_console" in your webpage:

<div id="opentok_console"></div>

Handling exception events

The TB object dispatches exception events when the OpenTok library encounters certain errors. Thefollowing adds a specific function as an event listener for the exception event:

TB.addEventListener("exception", exceptionHandler); function exceptionHandler(event) { TB.log(event.message);}

If you are interested in a specific type of exception, you can check the code property of theExceptionEvent object:

TB.addEventListener("exception", exceptionHandler); function exceptionHandler(event) { if (event.code == 1500) { // unable to publish TB.log(event.message); }}

You may want to take other actions than simply logging out the event's message property, as in theseexamples. For example, you may want to use a JavaScript debugger to set a breakpoint in the eventlistener for the exception event.

Using the staging environment

The OpenTok staging environment gives you certain advantages when developing and testing an app.

To use the staging environment, build your test app using the OpenTok JavaScript library loaded fromthe following URL: <script src="http://static.opentok.com/v0.91/js/TB.min.js"></script>.

With the staging environment, you can get started building your app, using the OpenTok JavaScriptlibrary only. You do not need to use the OpenTok server-side libraries at all. You can use the"devtoken" and "moderator_token" test token strings. You do not need to generate tokens using theOpenTok server-side libraries. For more information, see Content Token Creation.

The staging version of OpenTok JavaScript library is not minified (whereas the production version is).

OpenTok JavaScript API Tutorials and Sample Code 15

Copyright 2012 TokBox, Inc. All rights reserved. 6/13/2012

Page 16: Open tok api_tutorials

This makes it easier to read through the code and set breakpoints for debugging. For moreinformation, see the downloads page.

You can load a specific version of the OpenTok JavaScript library by modifying the version number inthe src attribute of the JavaScript script element. For more information, see the OpenTok JavaScriptAPI reference.

For more information, see Testing and Production.

Testing multiple client connections on one machine

Often, you will want to test your app using two client web pages. This lets you establish twoindependent pages that connect to the same OpenTok session. You can, for example, load the sameURL in two tabs in the same browser. Each page can independently connect to the same session.Each page is a unique client, with a unique connection to the app. Each page (given tokenpermissions) can publish a stream, and each can subscribe to the other's stream. (Each tab in thesame browser has access to the webcam and microphone, as long as no other browser or applicationare using them.)

Reporting issues to TokBox

Use the TB.reportIssue() method to submit an issue report to TokBox, as in the following code:

TB.reportIssue("We were unable to successfully publish.");

Upon successfully submitting an issue report to TokBox, the TB object dispatches an issueReportedevent, which is defined by the IssueReportedEvent class. The issueId property of the event is aunique identifier for the issue. Use this issue ID when discussing the issue with TokBox.

If the issue is not supported successfully (for example, due to no network connection), the TB objectdispatches an exception event. The code property of the event object is set to 2010.

Here is a more complete example that includes event listeners for the issueReported and exceptionevents:

TB.addEventListener("exception", exceptionHandler);TB.addEventListener("issueReported", issueReportedHandler);var description = "The user sees a No Video indicator in a subscriber.";TB.reportIssue(description);

function exceptionHandler(event) { if (event.code == 2010) { // The issue was not sent // This exception lets the developer know that the issue report // was not sent, perhaps due to a network error. }}

function issueReportedHandler(event) { // The developer may want to send the event.issueId string back to his server.}

OpenTok JavaScript API Tutorials and Sample Code 16

Copyright 2012 TokBox, Inc. All rights reserved. 6/13/2012

Page 17: Open tok api_tutorials

You can submit only one issue per client session. After that, calling this method results in nooperation.

The description is limited to 300 characters. Additional characters in the description parameter arenot submitted with the issue report.

The OpenTok JavaScript library automatically reports all exception events. There is no need to reportthem using the TB.reportIssue() method.

OpenTok JavaScript API Tutorials and Sample Code 17

Copyright 2012 TokBox, Inc. All rights reserved. 6/13/2012

Page 18: Open tok api_tutorials

JavaScript Tutorial — Pre-publish set-upThis tutorial shows how to test and configure the camera and microphone prior to publishing a videostream to a session:

You can add a Publisher object to the HTML DOM without streaming to a session.

You can check the available microphones and cameras on the client and specify which ones touse.

You can adjust the microphone gain and see the affect on the audio level.

To see a tutorial on how to publish or subscribe to a stream with audio or video only, see the Audio-only and Video-only tutorial.

Testing the tutorial online

To run the tutorial:

1. Make sure that you have a webcam connected to your computer and configured to run.

2. If the Flash Player Settings dialog is displayed, click the Allow button. This grants TokBox.comaccess to your camera and microphone.

3. Click the Manage devices button.

The page displays the Test mic and camera form.

4. You can change the selected microphone and selected camera (assuming your computer hasmore than one microphone and camera).

Select an active microphone and camera.

You can update the lists of microphones and cameras by clicking the Refresh device listslink.

5. Speak into the microphone and note the green mic level indicator. You can adjust themicrophone gain (enter a number from 0 to 100).

6. Close the Test mic and camera form.

7. Click the Start Publishing link.

The page is now publishing an audio-video stream to the session.

Testing the code on your own computer

See the instructions in the Hello World tutorial.

OpenTok JavaScript API Tutorials and Sample Code 18

Copyright 2012 TokBox, Inc. All rights reserved. 6/13/2012

Page 19: Open tok api_tutorials

Understanding the code

Note: You may want to look at the Basic Tutorial sample, if you have not already. It provides detailson many of the basic concepts, like connecting to an OpenTok session, publishing an audio-videostream, and subscribing to streams.

To understand the OpenTok JavaScript library is used, View the source for this browser page. Youcan also download the source for this Tutorial application (and for the other OpenTok tutorialapplications) by clicking the Download Source button at the top of this page.

Adding a Publisher without publishing to a session

The TB.initPublisher() method adds a Publisher object to the HTML DOM, but does not send anaudio-video stream to a session.

The first parameter of this method is the ID of the DOM element that the new Publisher object willreplace. In its init() function, the sample app creates a new DIV element as a child of the"publisherContainer" DIV, and adds the publisher to the page:

var parentDiv = document.getElementById("publisherContainer");var replacementDiv = document.createElement("div");replacementDiv.id = "opentok_publisher";parentDiv.appendChild(replacementDiv);

publisher = TB.initPublisher(apiKey, replacementDiv.id);

This Publisher object is not yet publishing a stream to an OpenTok session. (We will do that later.)You can use the Publisher to set up and test microphones and cameras. (The ability to initialize aPublisher object before you publish a stream was added in OpenTok v0.91.57.)

The next lines of code set up event listeners for the Publisher object. We will look at these eventslater:

publisher.addEventListener("devicesDetected", devicesDetectedHandler);publisher.addEventListener("microphoneActivityLevel", microphoneActivityLevelHandler)publisher.addEventListener("microphoneGainChanged", microphoneGainChangedHandler);publisher.addEventListener("echoCancellationModeChanged", echoCancellationModeChangedHandler);

Detecting available devices

The final line of the init() function calls the detectDevices() method of the Publisher object:

publisher.detectDevices()

The OpenTok library checks for available cameras and microphones. The Publisher object thendispatches a devicesDetected event. This event is defined by the DeviceStatusEvent class, and itincludes the following properties:

OpenTok JavaScript API Tutorials and Sample Code 19

Copyright 2012 TokBox, Inc. All rights reserved. 6/13/2012

Page 20: Open tok api_tutorials

cameras — An array of Camera objects corresponding to available cameras.

microphones — An array of Microphone objects corresponding to available microphones.

selectedCamera — The selected camera (a Camera object).

selectedMicrophone — The selected microphone (a Microphone object)

Each Camera and Microphone object has a name property, which is a string.

The event handler for the devicesDetected event adjusts the lists of the cameras and microphones inthe Manage devices user interface by adding option elements as children of the select elements:

function devicesDetectedHandler(event) { var microphones = event.microphones; var cameras = event.cameras; var camsSelect = document.getElementById("cams"); for (i = 0; i < cameras.length; i++) { var camOption = document.createElement("option"); camName = cameras[i].name; camOption.setAttribute("value", camName); camOption.innerHTML = camName; camsSelect.appendChild(camOption); if (camName == event.selectedCamera.name) { camsSelect.selectedIndex = i; } } var micSelect = document.getElementById("mics"); for (i = 0; i < microphones.length; i++) { var micOption = document.createElement("option"); var micName = microphones[i].name; micOption.setAttribute("value", micName); micOption.innerHTML = micName; micSelect.appendChild(micOption); if (micName == event.selectedMicrophone.name) { micSelect.selectedIndex = i; } }}

Changing the microphone and camera used by the Publisher

In the Manage devices form, the user can set the microphone and camera used by the Publisher.When the user selects a value from the microphones list, the code calls the setMicrophone() methodof the Publisher, passing in the name of the selected microphone from the drop-down list:

function setMicrophone() { var micsSelect = document.getElementById("mics"); var micName = micsSelect.options[micsSelect.selectedIndex].value; publisher.setMicrophone(micName);}

The values of the options in the drop-down list were populated with names from thedevicesDetected event.

Similarly, when the user selects a value from the cameras list, the code calls the setCamera() methodof the Publisher, passing in the name of the selected camera from the drop-down list:

OpenTok JavaScript API Tutorials and Sample Code 20

Copyright 2012 TokBox, Inc. All rights reserved. 6/13/2012

Page 21: Open tok api_tutorials

function setCamera() { var camsSelect = document.getElementById("cams"); var cameraName = camsSelect.options[camsSelect.selectedIndex].value; publisher.setCamera(cameraName);}

Detecting the microphone level and setting the microphone gain

When you display the Manage devices form, the code calls the detectMicActivity() method of thePublisher (passing in the value true):

publisher.detectMicActivity(true);

This causes the Publisher to dispatch microphoneActivityLevel events that periodically report theinstantaneous microphone activity level. A level of 0 is silent, a level of 100 is full activity. The eventhandler for the event adjusts a volume meter DIV in the user interface:

function microphoneActivityLevelHandler(event) { var volumeIndictator = document.getElementById("volumeIndicator"); var volumeLevel = event.value * microphoneGain / 100; volumeIndictator.style.width = volumeLevel + "%";}

The user can adjust the value of the gainControl input element, and in response, the code calls thesetMicrophoneGain() method of the publisher object. This adjusts the microphone gain used by thePublisher, based on the value set by the user:

function setMicrophoneGain() { var gainControl = document.getElementById("gainControl"); publisher.setMicrophoneGain(gainControl.value);}

Also, if the microphone gain changes due to the user adjusting the slider in the Publisher userinterface, the publisher dispatches a microphoneGainChanged event. The event handler for this eventadjusts the value of the gainControl input element:

function microphoneGainChangedHandler(event) { microphoneGain = event.value; var gainControl = document.getElementById("gainControl"); gainControl.value = microphoneGain;}

Detecting the echo suppression setting

Once you publish a stream to the session, the Publisher dispatches an echoCancellationModeChangedevent when the OpenTok JavaScript library determines the echo suppression mode of the publisher.It also dispatches this event if the echo cancellation mode changes.

The event handler for the echoCancellationModeChanged event is dispatched. You can then call thegetEchoCancellationMode() method of the Publisher to determine the current echo cancellationsetting. If this method returns "fullDuplex", then acoustic echo cancellation is active:

OpenTok JavaScript API Tutorials and Sample Code 21

Copyright 2012 TokBox, Inc. All rights reserved. 6/13/2012

Page 22: Open tok api_tutorials

function echoCancellationModeChangedHandler(event) { if (publisher.getEchoCancellationMode() == "fullDuplex") { document.getElementById("call-status").innerHTML = "Publishing: echo cancellation active."; } else { document.getElementById("call-status").innerHTML = "Publishing: echo cancellation mode inactive"; }}

OpenTok JavaScript API Tutorials and Sample Code 22

Copyright 2012 TokBox, Inc. All rights reserved. 6/13/2012

Page 23: Open tok api_tutorials

JavaScript Tutorial — Moderation and SignalingThis tutorial shows how to use the OpenTok JavaScript library to do the following:

Moderate a session, by disconnecting a connection

Have a connection send a signal to other connections

Testing the tutorial online

To run the tutorial:

1. Make sure that you have a webcam connected to your computer and configured to run.

2. Click the Connect link.

This connects you to the OpenTok session. The TokBox API logs a message on the page:"Connected to the session."

3. Click the Publish link.

If the Flash Player Settings dialog is displayed, click the Allow button and then click theClose button. This grants TokBox.com access to your camera and microphone.

You are now publishing a video stream to the session, and the video stream is displayed onthe page.

4. Copy the URL for this page into the Clipboard.

5. Open a new browser window, and have it open to the copied URL.

6. Click the Connect link (in the new browser window).

The new page now connects to the session. Upon connection the video stream from theother page is displayed on the page.

7. Click the Signal link.

The connection on the page sends a signal to all connections. Upon receiving the signal,each of the two pages displays a JavaScript alert ("Received a signal..."). Click the OKbutton in the alert dialog box.

8. Click the Disconnect link, underneath the displayed video stream (in the second browserwindow).

Testing the code on your own computer

See the instructions in the Hello World tutorial.

OpenTok JavaScript API Tutorials and Sample Code 23

Copyright 2012 TokBox, Inc. All rights reserved. 6/13/2012

Page 24: Open tok api_tutorials

Understanding the code

Note: You may want to look at the Basic Tutorial sample, if you have not already. It provides detailson many of the basic concepts, like connecting to an OpenTok session, publishing an audio-videostream, and subscribing to streams.

To understand how the OpenTok JavaScript library is used, View the source for this browser page.You can also download the source for this Tutorial application (and for the other OpenTok tutorialapplications) by clicking the Download Source button at the top of this page.

Sending a signal to the TokBox session

When you click the Signal link in the page, the a tag calls the signal() function:

<a href="javascript:signal();" id="signalLink">Signal</a>

The signal() function calls the signal() method of the OpenTok Session object:

function signal() { session.signal();}

The call to session.signal() sends a signal to the OpenTok session. Other connections to the sessioncan set up event listeners to receive this signal.

Note: For information on code that initiates a TokBox session, connects to the session, see the Basictutorial.

Receiving a signal from the TokBox session

When the page has connected to the TokBox session, (when the session object dispatches asessionConnected event), the sessionConnectedHandler() function is called. This function includescode for adding an event listener for the signalReceived event:

session.addEventListener("signalReceived", signalReceivedHandler);

When any connection in the session sends a signal (using the signal() method of the Session object),the session object on this page dispatches a signalReceived event. The previous code registers thesignalReceivedHandler() function.

The code defines a signalReceivedHandler() function as follows:

function signalReceivedHandler (event) { alert("Received a signal from connection " + event.fromConnection.connectionId);}

OpenTok JavaScript API Tutorials and Sample Code 24

Copyright 2012 TokBox, Inc. All rights reserved. 6/13/2012

Page 25: Open tok api_tutorials

Disconnecting a session

Upon connecting to a session, the code calls the () handler for the sessionConnected event:

function sessionConnectedHandler(event) { document.getElementById("publisherDiv").innerHTML += "<br/>Connected to the session";

for (var i = 0; i < event.streams.length; i++) { addStream(event.streams[i]); }}

This function calls the addStream() function. This function constructs a div tag that contains the videofor a stream as well as as Force Disconnect link for the stream:

function addStream(stream) { if (stream.connection.connectionId == session.connection.connectionId) { show("unpublishLink"); return; } // Create the container for the subscriber var container = document.createElement('div'); container.className = "subscriberContainer"; var containerId = "container_" + stream.streamId; container.setAttribute("id", containerId); document.getElementById("subscriberBar").appendChild(container);

// Create the div that will be replaced by the subscriber var div = document.createElement('div'); var divId = stream.streamId; div.setAttribute('id', divId); div.style.float = "top"; container.appendChild(div);

// Create a div for the force disconnect link var forceDisconnect = document.createElement('div'); forceDisconnect.style.float = "bottom"; forceDisconnect.innerHTML = '<a href="#" onClick="javascript:forceDisconnectStream(\'' + stream.streamId + '\')">Force Disconnect</a>' + '<a href="#" onclick="javascript:forceUnpublishStream(\'' + stream.streamId + '\')">Force Unpublish</a>' container.appendChild(forceDisconnect);

subscribers[stream.streamId] = session.subscribe(stream, divId);}

When the user clicks the Force Disconnect link, the a tag calls the forceDisconnectStream() function.This method calls the forceDisconnect() method of the Session object:

function forceDisconnectStream (streamId) { session.forceDisconnect(subscribers[streamId].stream.connection.connectionId);}

The forceDisconnect() method of the Session object is part of the OpenTok JavaScript library. It tellsthe OpenTok session to disconnect the specified connection. In this case, the code maintains an arrayof streams based on stream IDs. (When generating the HTML containing the Force Disconnect link,the addStream() function added the stream ID as an identifier for a stream.

OpenTok JavaScript API Tutorials and Sample Code 25

Copyright 2012 TokBox, Inc. All rights reserved. 6/13/2012

Page 26: Open tok api_tutorials

Forcing a participant to stop publishing a stream

The code described in the previous section adds a "Force Disconnect" link for each subscribedstream:

When the user clicks the Force Unpublish button, the a tag calls the forceUnpublishStream()function. This method calls the forceDisconnect() method of the Session object:

function forceUnpublishStream(streamId) { session.forceUnpublish(subscribers[streamId].stream);}

The forceUnpublish() method of the Session tells the OpenTok session to force the user to stoppublishing the specified stream.

Note that forceDisconnect() and forceUnpublish methods are only available to users that havelogged in with a token that has the moderation role assigned to it. You assign roles to tokens usingthe OpenTok server-side library. While testing your app, using the OpenTok staging server, you canuse the "moderator_token" test token string, as is used in this demo.

Detecting when a user has been forced to disconnect

The SessionDisconnectEvent object has a reason property. This is set to "forceDisconnected" if theuser's session was disconnected through a moderator calling forceDisconnect(). You can check thisreason in the event handler:

if (event.reason == "forceDisconnected") { alert("A moderator has disconnected you from the session.");}

Detecting when a user has been forced to unpublish

The StreamEvent object has a reason property. This is set to "forceUnpublisheded" if the streamsession was disconnected through a moderator calling forceUnpublish(). You can check this reason inthe event handler:

for (var i = 0; i < event.streams.length; i++) { removeStream(event.streams[i].streamId); if (event.streams[i].connection.connectionId == session.connection.connectionId && event.reason == "forceUnpublished") { alert("A moderator has stopped publication of your stream."); hide("unpublishLink"); show("publishLink"); publisher = null; }}

OpenTok JavaScript API Tutorials and Sample Code 26

Copyright 2012 TokBox, Inc. All rights reserved. 6/13/2012

Page 27: Open tok api_tutorials

JavaScript Tutorial — Resizing videoThis tutorial shows how you can control the size of the OpenTok video display, just as you would anyother HTML element. Also, it demonstrates that you can show an OpenTok video multiple times inthe web page.

Testing the tutorial online

To run the tutorial:

1. Make sure that you have a webcam connected to your computer and configured to run.

2. Click the Start publishing link.

If the Flash Player Settings dialog is displayed, click the Allow button. This grantsTokBox.com access to your camera and microphone.

You are now publishing a video stream to the session, and the video stream is displayedmultiple times on the page, in different sizes.

As you follow the diagonal up and to the left from that corner, you can see scaled-down versions ofthe published stream, each of which maintains the original 4:3 aspect ratio.

For containers that display a stream with dimensions that do not match the 4:3 aspect ratio, thevideo image is be clipped. The video image is clipped so that the center-most part of the image isdisplayed. You can see this in some of the video displays of the movie.

Testing the code on your own computer

See the instructions in the Hello World tutorial.

Understanding the code

Note: You may want to look at the Basic Tutorial sample, if you have not already. It provides detailson many of the basic concepts, like connecting to an OpenTok session, publishing an audio-videostream, and subscribing to streams.

A subscriber_width array and a subscriber_height array define the widths and heights to use for thedisplayed videos:

var subscriber_width = [120, 160, 220];var subscriber_height = [90, 120, 165];

When you publish a stream, the Session object (defined in the Tokbox JavaScript library) dispatches astreamCreated event. The streamCreatedHandler() is the event handler for this event.

OpenTok JavaScript API Tutorials and Sample Code 27

Copyright 2012 TokBox, Inc. All rights reserved. 6/13/2012

Page 28: Open tok api_tutorials

function streamCreatedHandler(event) { for (var i = 0; i < event.streams.length; i++) { if (event.streams[i].connection.connectionId == event.target.connection.connectionId) { for (y = 0; y < 3; y++) { for (x = 0; x < 3; x++) { // Create a div for the subscriber to replace var parentDiv = document.getElementById("cell_" + x + "_" + y); var subscriberDiv = document.createElement("div"); subscriberDiv.id = "opentok_subscriber_" + x + "_" + y; parentDiv.appendChild(subscriberDiv);

var subscriberProps = {width: subscriber_width[x], height: subscriber_height[y], subscribeToAudio: false}; event.target.subscribe(event.streams[i], subscriberDiv.id, subscriberProps); } } } }}

The StreamEvent object, which defines the streamCreated event, has a streams property. Thisproperty is an array of Stream objects. The streamCreatedHandler() function checks each Streamobject in the array to see if it matches the stream you just published. It does this by comparing theconnection ID for the stream with that of your own connection. (Each user's connection to thesession has a connection ID.) For more information on Session and Stream objects, see the Basictutorial.

If the code finds a stream that matches your session (one that you published), it iterates through thecells of the HTML table. For each cell, the code creates a container div and calls the subscribe()method of the Session object. This adds the video to the page.

The last parameter of the subscribe() method is the properties parameter. The width and heightproperties of this object determine the width and height of the video displayed. Note that the codeobtains these values from the subscriber_width and subscriber_height arrays:

var subscriberProps = {width: subscriber_width[x], height: subscriber_height[y], subscribeToAudio: false};

OpenTok JavaScript API Tutorials and Sample Code 28

Copyright 2012 TokBox, Inc. All rights reserved. 6/13/2012

Page 29: Open tok api_tutorials

JavaScript Tutorial — Audio-only and Video-onlyThis tutorial shows how to publish a video as audio-only or video-only. It also shows how to changethe local playback of a subscribed stream to audio-only or video-only.

For more information on controlling audio, see the Controlling Audio tutorial.

Testing the tutorial online

To run the tutorial:

1. Make sure that you have a webcam connected to your computer and configured to run.

2. Click the Connect button.

3. Wait for the page to connect to the session. Then choose the Audio-only option and click theStart Publishing button.

If the Flash Player Settings dialog is displayed, click the Allow button and then click theClose button. This grants TokBox.com access to your camera and microphone.

You are now publishing an audio-only stream to the session, and the video streamplaceholder is displayed on the page.

4. Copy the URL for this page into the Clipboard.

5. Open a new browser window, and have it open to the copied URL.

Better yet ... have another user open the URL in a browser on another computer. If you areconnecting on the same computer, be sure to wear headphones, to avoid audio feedback.

The new page now connects to the session. Upon connection the stream, the video-onlyplaceholder from the first page is displayed on the new page.

6. Go back to the first page and click the Turn on my video link. Then click the Turn off my audiolink.

7. Go to the second page and note that the stream is now video-only.

8. Go back to the first page and click the Turn on my audio link.

9. Go to the second page and note that audio and video are published again.

10. Click the Turn off audio link for the subscribed video.

The second page now retrieves a video-only stream.

11. Click the Turn on audio link for the subscribed video.

OpenTok JavaScript API Tutorials and Sample Code 29

Copyright 2012 TokBox, Inc. All rights reserved. 6/13/2012

Page 30: Open tok api_tutorials

The second page now plays both audio and video.

12. Click the Turn off video link for the subscribed video.

The second page now retrieves an audio-only stream.

Testing the code on your own computer

See the instructions in the Hello World tutorial.

Understanding the code

Note: You may want to look at the Basic Tutorial sample, if you have not already. It provides detailson many of the basic concepts, like connecting to an OpenTok session, publishing an audio-videostream, and subscribing to streams.

To understand the OpenTok JavaScript library is used, View the source for this browser page. Youcan also download the source for this Tutorial application (and for the other OpenTok tutorialapplications) by clicking the Download Source button at the top of this page.

Setting the initial publishing mode: audio-only, video-only, or audio/video

When the user clicks the Start publishing button, it invokes the click event handler, thestartPublishing() function. It sets up the div objects and other objects needed to start publishing,which you do by calling the publish() method of the Session object. The publish() method has anoptional properties parameter. The object you pass to this parameter has optional publishAudio andpublishVideo properties, which determine whether the stream initially publishes audio or video (orboth). The startPublishing function sets these properties based on the user's radio-buttonselections. It then passes the publish properties to the publish() method of the Session object:

var publisherProperties = new Object();if (document.getElementById("pubAudioOnly").checked) { publisherProperties.publishVideo = false;}if (document.getElementById("pubVideoOnly").checked) { publisherProperties.publishAudio = false;}

publisher = TB.initPublisher(apiKey, publisherDiv.id, publisherProperties);session.publish(publisher);

The method also calls the getPublisherControls() function, which creates a set of links to togglevideo and audio for the published stream.

function getPublisherControls() { sessionControlsDiv = document.createElement('div'); sessionControlsDiv.innerHTML = '' + '' + '' + '' return sessionControlsDiv;

OpenTok JavaScript API Tutorials and Sample Code 30

Copyright 2012 TokBox, Inc. All rights reserved. 6/13/2012

Page 31: Open tok api_tutorials

}

Toggling publishing of audio and video

When the stream you publish is created (when the Session dispatches the streamCreated event foryour stream), the code makes the Turn on/off my audio and Turn on/off my video links visible. Theevent listener for the streamCreated event determines which links (for example "Turn on my audio"or "Turn off my audio") to display, based on the user's settings.

The onClick handler for the Turn off my audio link calls the following code:

publisher.publishAudio(false)

The onClick handler for the Turn on my audio link calls the following code:

publisher.publishAudio(true)

The publishAudio() method of the Publisher object turns publishing of audio on and off based on thevalue you pass (true or false).

Similarly, the onClick handler for the Turn off my video link calls publisher.publishVideo(false).And the onClick handler for the Turn on my video link calls publisher.publishVideo(true).

Toggling audio and video in subscribed streams

When another user's stream is created (when the Session dispatches the streamCreated event foranother user's stream), the code makes the Turn off audio and Turn off video links visible for thesubscribed stream. The visibility of these links is based on the hasAudio property of the Streamobject. (If the stream does not have audio, the links are hidden.)

var audioControlsDisplay;if (stream.hasAudio) { audioControlsDisplay = "block";} else { audioControlsDisplay = "none";}var videoControlsDisplay;if (stream.hasVideo) { videoControlsDisplay = "block";} else { videoControlsDisplay = "none";}actionDiv.innerHTML = '<span id="' + streamId +'-audioControls" style="display:' + audioControlsDisplay + '"> \ <a href="#" id="'+streamId+'-audioOff" onclick="turnOffHerAudio(\''+streamId+'\');" style="display:block">Turn off audio</a>\ <a href="#" id="'+streamId+'-audioOn" onclick="turnOnHerAudio(\''+streamId+'\')" style="display:none">Turn on audio</a>\ </span> \ <span id="' + streamId +'-videoControls" style="display:' + videoControlsDisplay + '"> \ <a href="#" id="'+streamId+'-videoOff" onclick="turnOffHerVideo(\''+streamId+'\')" style="display:block">Turn off video</a>\ <a href="#" id="'+streamId+'-videoOn" onclick="turnOnHerVideo(\''+streamId+'\')"

OpenTok JavaScript API Tutorials and Sample Code 31

Copyright 2012 TokBox, Inc. All rights reserved. 6/13/2012

Page 32: Open tok api_tutorials

style="display:none">Turn on video</a>\ </span>';

The event handler for the streamPropertyChanged event toggles the visibility of the subscriber audioand video links, based on the changed property and the new value:

function streamPropertyChangedHandler(event){ var stream = event.stream; var audioControls = document.getElementById(stream.streamId + "-audioControls"); if (audioControls && event.changedProperty == "hasAudio") { if (event.newValue == true) { audioControls.style.display = "block"; } else { audioControls.style.display = "none"; } } else if (audioControls && event.changedProperty == "hasVideo") { if (event.newValue == true) { audioControls.style.display = "block"; } else { audioControls.style.display = "none"; } }}

The onClick handler for the Turn off audio link calls the following code:

subscriber.subscribeToAudio(false)

The subscribeToAudio() method of the Subscriber object turns subscribing to audio on and off basedon the value you pass (true or false). Note that this method only affects inward streaming of audioon the local page. It does not affect the publisher's streaming or other user's pages.

The onClick handler for the Turn on audio link calls the following code:

subscriber.subscribeToAudio(true)

Similarly, the onClick handler for the Turn off video link calls subscriber.subscribeToVideo(false).And the onClick handler for the Turn on video link calls subscriber.subscribeToVideo(true).

OpenTok JavaScript API Tutorials and Sample Code 32

Copyright 2012 TokBox, Inc. All rights reserved. 6/13/2012

Page 33: Open tok api_tutorials

JavaScript Tutorial — Passing user informationThis tutorial shows how to set and retrieve metadata for each client connecting to a session.

Testing the tutorial online

To run the tutorial:

1. Make sure that you have a webcam connected to your computer and configured to run.

2. Enter your name (up to 12 characters). Then select a color from the drop-down list.

3. Click the Connect button.

The page connects to the session.

4. Click the Start Publishing button.

If the Flash Player Settings dialog is displayed, click the Allow. This grants TokBox.comaccess to your camera and microphone.

You are now publishing a video stream to the session, and the video stream is displayed onthe page.

5. Copy the URL for this page into the Clipboard.

6. Open a new browser window, and have it open to the copied URL.

Be sure to wear headphones or to mute the speaker.

7. In the new page, enter another name and select a color from the drop-down list.

8. Click the Connect button.

The new page now connects to the session. Upon connection the video stream from thefirst page is displayed in the new browser page. Underneath the video the page displaysthe first name and selected color. This was sent to the second page as metadata for theconnection.

The page also displays a "Connected users" list that displays the metadata (name and color)for all connections to the session (other than the current client's metadata).

Testing the code on your own computer

See the instructions in the Hello World tutorial.

Understanding the code

OpenTok JavaScript API Tutorials and Sample Code 33

Copyright 2012 TokBox, Inc. All rights reserved. 6/13/2012

Page 34: Open tok api_tutorials

Note: You may want to look at the Basic Tutorial sample, if you have not already. It provides detailson many of the basic concepts, like connecting to an OpenTok session, publishing an audio-videostream, and subscribing to streams.

To understand the OpenTok JavaScript library is used, view the source for this browser page. You canalso download the source for this Tutorial application (and for the other OpenTok tutorialapplications) by clicking the Download Source button at the top of this page.

Setting metadata for a connection

The user sets the metadata using HTML controls included in a DIV element that is visible when theuser first opens the page:

<div id="login"> <p>Enter your name: <input type="text" id="username" maxlength="12"/> </p> <p>Select a color: <select id="colorSelect"> <option selected="selected">Blue</option> <option>Green</option> <option>Orange</option> <option>Purple</option> <option>Red</option> <option>Yellow</option> </select> </p> <p><input type="button" value="Connect" id ="connectLink" onClick="javascript:connect()" /></p> <p id="warning" style="display:none; color:#F00">Please enter your name.</p></div>

When using a test the OpenTok staging server, you can pass the connection metadata when you callthe connect() method of the Session object (in the last line of the connect() function definition, fromthe source code):

function connect() { var usernameField = document.getElementById("username"); var colorSelect = document.getElementById("colorSelect"); var sessionContent = document.getElementById("sessionContent");

var userProperties = {username: usernameField.value, color: colorSelect.value}; try { var connectionData = JSON.stringify(userProperties); } catch (error) { connectionData = '{' + '"username":"' + usernameField.value + '", "color":"' + colorSelect.value + '"}'; } var sessionConnectProperties = {connectionData:connectionData}; session.connect(API_KEY, TOKEN, sessionConnectProperties);}

This sample application sets the data to a JSON string:

var userProperties = {username: usernameField.value, color: colorSelect.value};try { var connectionData = JSON.stringify(userProperties);} catch (error) {

OpenTok JavaScript API Tutorials and Sample Code 34

Copyright 2012 TokBox, Inc. All rights reserved. 6/13/2012

Page 35: Open tok api_tutorials

connectionData = '{' + '"username":"' + usernameField.value + '", "color":"' + colorSelect.value + '"}';}

Not all browsers support the JSON.stringify() method, in which case the code sets the JSON stringusing a less secure method.

You can format your own data as is best suited for your application. For example, instead of usingJSON, you could format the string using comma-separated key-value pairs or using XML.

Sending data securely

Setting the metadata when calling the connect() method only works when you are using a test tokenstring in with the OpenTok staging environment. When you switch to using a generated user token(which is required in the OpenTok production environment), you set the connection metadata whenyou generate the token, using the generate_token() method in the OpenTok server-side libraries.

When you set the metadata using the generate_token() method, the metadata is securely encoded inthe token string. It cannot be tampered with in JavaScript code. Metadata passed to the connect()method of the client-side JavaScript Session object is ignored.

The following example sets the metadata string using the generate_token() method of the OpenTokserver-side PHP library:

<?PHP

require_once 'OpenTokSDK.php';

$token = new OpenTokSDK(API_Config::API_KEY, API_Config::API_SECRET);$role = RoleConstants::PUBLISHER; // Or set to the correct role for the user.$metadata = '{"username": "bob", "color": "Blue"}'print $token->generate_token('your_session_ID', $role, NULL, $metadata); // Replace with the correct session IDprint "\n";

Note however that you will probably want to populate the string with values that you obtain from adatabase or that you record from the user in some other way.

This sample does not include server-side code. It sets the metadata using JavaScript on the client side(as described above), which is OK when using the 'devtoken' test token string and the OpenTokstaging enviroment. When you switch to generating individual user tokens, be sure to add themetadata string to the call to the server-side generate_token() method.

Getting data for other clients

Let's get back to looking at client-side JavaScript code.

When a client connects to the session, the Session object (in each client page) dispatches aconnectionCreated event. This event is defined by the ConnectionEvent class. It has a connectionsproperty which is an array of Connection objects. Each Connection object has a data property that isthe metadata associated with the new connection.

OpenTok JavaScript API Tutorials and Sample Code 35

Copyright 2012 TokBox, Inc. All rights reserved. 6/13/2012

Page 36: Open tok api_tutorials

The sample app sets up an event listener for the connectionCreated event. This event listener in turncalls the addConnection() function, which posts the metadata to the webpage, in a Connected Userslisting:

function connectionCreatedHandler(event) { for (i = 0; i < event.connections.length; i++) { addConnection(event.connections[i]); }}

function addConnection(connection) { if (connection.connectionId != session.connection.connectionId) { var connectionListing = document.createElement('p'); connectionData = getConnectionData(connection); connectionListing.style.margin = "0px 0px 2px 4px"; connectionListing.innerHTML = connection.connectionId; connectionListing.innerHTML = connectionData.username + ' (' + connectionData.color + ')'; connectionListing.setAttribute("id", connection.connectionId); document.getElementById("connections").appendChild(connectionListing); }}

The getConnectionData() method parses the JSON data from the data property of the Connectionobject:

function getConnectionData(connection) { try { connectionData = JSON.parse(connection.data); } catch(error) { connectionData = eval("(" + connection.data + ")" ); } return connectionData;}

Again, older browsers do not support the JSON.parse() method, and in that case the function usesthe eval() function to parse the JSON data (which can be less secure). However, your code maycreate the metadata in other formats, such as XML or comma-delimited key-value pairs.

When a client publishes an audio-video stream, the Session object in each other connected client'spage dispatches a streamCreated event. For each new stream created (aside from the client's ownstream), the event listener for the streamCreated event calls the addStream() function:

function streamCreatedHandler(event) { for (var i = 0; i < event.streams.length; i++) { addStream(event.streams[i]); }}

In addition to subscribing to the new stream, the addStream() function displays the metadata for theclient publishing the stream. It obtains this from the data property of the connection property of theStream object:

var subscriberData = document.createElement('div');subscriberData.style.cssFloat = "bottom";var connectionData = getConnectionData(stream.connection);

OpenTok JavaScript API Tutorials and Sample Code 36

Copyright 2012 TokBox, Inc. All rights reserved. 6/13/2012

Page 37: Open tok api_tutorials

subscriberData.style.margin = "0px 0px 2px 4px";subscriberData.innerHTML = connectionData.username + ' (' + connectionData.color + ')';container.style["border"] = "medium solid " + colorStringToHexString(connectionData.color);container.appendChild(subscriberData);

The code also adds a colored border for each subscriber, based on the color specified in theconnection metadata.

When connections and streams are destroyed in the session, event listeners for theconnectionDestroyed and streamDestroyed events remove the metadata displayed for the associatedconnections and streams.

OpenTok JavaScript API Tutorials and Sample Code 37

Copyright 2012 TokBox, Inc. All rights reserved. 6/13/2012

Page 38: Open tok api_tutorials

JavaScript Tutorial — Recording stand-alonearchives

This tutorial shows how to use the OpenTok JavaScript library to record and play back stand-alonearchives. A stand-alone archive is a recording of an audio-video stream that you make outside of anOpenTok session. You can then play the stand-alone archive on its own (outside of a session); or youcan play it back in an OpenTok session, so that all connected clients can view it.

The OpenTok archiving API is in beta testing. For more information, see the Archiving overview.

Testing the tutorial online

1. Open the page in a browser.

When you first open the page, it displays the OpenTok Recorder, which lets you createstand-alone recordings.

If the Flash Player Settings dialog box is displayed, click the Allow button and then click theClose button. This grants tokbox.com access to your camera and microphone.

2. Click the red Record button at the bottom of the Recorder.

You are now recording a stand-alone archive.

3. Wait at least 10 seconds, and then click the Stop button at the bottom of the Recorder.

4. Click the Save button at the bottom of the Recorder.

The OpenTok library saves the archive to the OpenTok servers. A screenshot of therecording appears below the Recorder.

5. Click the screenshot of the recording.

The archive plays back in the OpenTok stand-alone archive Player.

Testing the code on your own computer

See the instructions in the Hello World tutorial.

Understanding the code

Note: You may want to look at the Basic Tutorial sample, if you have not already. It provides detailson many of the basic concepts, like connecting to an OpenTok session, publishing an audio-video

OpenTok JavaScript API Tutorials and Sample Code 38

Copyright 2012 TokBox, Inc. All rights reserved. 6/13/2012

Page 39: Open tok api_tutorials

stream, and subscribing to streams.

To understand how the OpenTok JavaScript library is used, view the source for this browser page.You can also download the source for this Tutorial application (and for the other OpenTok tutorialapplications) by clicking the Download Source link at the top of this page.

Recording stand-alone archives

First, instantiate a RecorderManager object by calling TB.initRecorderManager(). The init() functionin the page does this when the page is loaded:

recorderManager = TB.initRecorderManager(API_KEY);

The RecorderManager object lets you add an OpenTok Recorder or an OpenTok Player to your page.The createRecorder() function adds a Recorder to the page by calling the displayRecorder() methodof the RecorderManager object.

function createRecorder() { var recDiv = document.createElement('div'); recDiv.setAttribute('id', 'recorderElement'); document.getElementById('recorderContainer').appendChild(recDiv); recorder = recorderManager.displayRecorder(TOKEN, recDiv.id); recorder.addEventListener('recordingStarted', recStartedHandler); recorder.addEventListener('archiveSaved', archiveSavedHandler);}

First the code creates a DIV element that will be replaced by the OpenTok Recorder and adds it as achild of the 'recorderContainer' element. Then the code calls the displayRecorder() method of theRecorderManager object. The first parameter is an OpenTok token string. The token must includethe "moderator" role to successfully display an OpenTok Recorder. In this sample, the token string isset to the "moderator_token" test string. (For more information, see Connection Token Creation.) Thesecond parameter is the ID of the replacement HTML DOM element.

When the user starts recording, the Recorder object dispatches a recordingStarted event. The eventlistener for this event calls the getImgData() method of the Recorder object:

function recStartedHandler(event) { recImgData = recorder.getImgData();}

The getImgData() method returns a base-64-encoded string of PNG data representing the Recordervideo.

When the user saves the archive, the Recorder object dispatches a archiveSaved event. The eventlistener for this event adds the screen capture image to the page:

function archiveSavedHandler(event) { document.getElementById('archiveList').style.display = 'block'; var aLink = document.createElement('a'); aLink.setAttribute('href', "javascript:loadArchiveInPlayer(\"' + event.archives[0].archiveId + '\")');

OpenTok JavaScript API Tutorials and Sample Code 39

Copyright 2012 TokBox, Inc. All rights reserved. 6/13/2012

Page 40: Open tok api_tutorials

var recImg = getImg(recImgData); recImg.setAttribute('style', 'width:80; height:60; margin-right:2px'); aLink.appendChild(recImg); document.getElementById('archiveList').appendChild(aLink);}

The show() function simply makes HTML elements visible:

function show(id) { document.getElementById(id).style.display = 'block';}

The HTML generated by the archiveSavedHandler looks like this:

<a href="javascript:loadArchive('archiveID')"><img style="width: 80px; height: 60px; margin-right: 2px;" src="imageData"></a>

When the user clicks the link, it will cause the page to display an OpenTok Player for the archive (seethe next section).

In your application, you may want to save the archive ID and the PNG image data on your server. Youcan then retrieve the data later when you want to play back the archive ID in a future session (or ifyou want to display a preview thumbnail image of the archive).

Playing back stand-alone archives in the Player

The loadArchiveInPlayer() method creates an OpenTok Player object by calling the displayPlayer()method of the RecorderManager object:

function loadArchiveInPlayer(archiveId) { if (!player) { playerDiv = document.createElement('div'); playerDiv.setAttribute('id', 'playerElement'); document.getElementById('playerContainer').appendChild(playerDiv) player = recorderManager.displayPlayer(archiveId, TOKEN, playerDiv.id); document.getElementById('playerContainer').style.display = 'block'; else { player.loadArchive(archiveId); }}

The first parameter of the displayPlayer() method is the archive ID of the stand-alone archive youwish to play back. The second parameter of the displayPlayer() method is an OpenTok token string.The token must include the "moderator" role to successfully display an OpenTok Player. In thissample, the token string is set to the "moderator_token" test string. (For more information, seeConnection Token Creation.) The third parameter is the ID of the replacement HTML DOM element.

If the Player object has already been created, the loadArchiveInPlayer() function calls theloadArchive() method of the Player object. This loads the selected archive in the Player.

Playing back stand-alone archives in an OpenTok session

You can also play back a stand-alone recording in an OpenTok session. The recording plays back in

OpenTok JavaScript API Tutorials and Sample Code 40

Copyright 2012 TokBox, Inc. All rights reserved. 6/13/2012

Page 41: Open tok api_tutorials

the session as a stream that clients can subscribe to. This lets all participants in a session view therecording play back simultaneously. However, this sample application does not include code for this— it only plays the recording in the stand-alone player.

Call the loadArchive() method of the Session object loads the archive in the session. When thearchive is loaded, the Session object dispatches a archiveLoaded event. You can then call thestartPlayback() method of the Archive object (which is the archives[0] property of thearchiveLoaded event object):

session.addEventListener("archiveLoaded", archiveLoadedHandler);session.loadArchive(archiveId);

function archiveLoadedHandler(event) { archive = event.archives[0]; archive.startPlayback();}

Note: The API key you used when creating the stand-alone recording (by callingTB.initRecorderManager() method) must match the API used when you create the OpenTok session(using the server-side API). Only a client that connects to a session with a token that has beenassigned the role of moderator can load archives (using the Session.loadArchive() method).

The Session object dispatches a streamCreated event when the archive stream starts playing back. Inthe event handler for the streamCreated event, subscribe to the stream, just as you would subscribeto a live stream in the session. (You can differentiate between a live stream and a recoded stream bythe type property of the Stream object. (The type property is set to "archive" for an archive playbackstream.) For example, in the following code, the streamCreatedHandler() function is assumed to bethe event listener for the streamCreated event. The addStream() function then subscribes to streams(and labels them as either "live" or "recorded").

function streamCreatedHandler(event) { // Subscribe to the newly created streams for (var i = 0; i < event.streams.length; i++) { addStream(event.streams[i]); }}

function addStream(stream) { // Check if this is the stream that I am publishing, and if so do not subscribe. if (stream.connection.connectionId == session.connection.connectionId) { return; }

// Create the container for the subscriber var container = document.createElement('div'); var containerId = 'container_' + stream.streamId; container.setAttribute('id', containerId); container.className = 'swfContainer';

// The following assumes that there is a DOM element named "subscribersContainer". var subscribersContainer = document.getElementById('subscribersContainer'); subscribersContainer.appendChild(container);

// Create the div that will be replaced by the subscriber var div = document.createElement('div'); var divId = stream.streamId; div.setAttribute('id', divId); div.style.float = 'top';

OpenTok JavaScript API Tutorials and Sample Code 41

Copyright 2012 TokBox, Inc. All rights reserved. 6/13/2012

Page 42: Open tok api_tutorials

container.appendChild(div);

// Label the stream as "Recorded" or "Live." var label = document.createElement('p'); label.style.marginTop = '0px'; switch (stream.type) { case 'archive' : label.innerHTML = 'Recorded'; break; case 'basic' : label.innerHTML = 'Live'; break; } container.appendChild(label);

subscribers[stream.streamId] = session.subscribe(stream, divId);}

More OpenTok archiving features

Stand-alone recordings are just one feature of the OpenTok archiving API. You can also record andplay back OpenTok sessions. To see this in action, see Getting Started with the OpenTok ArchivingAPI. For more information, see the Archiving overview.

For more information on stand-alone archives, see Recording and playing back stand-alone archives.Also see the Recorder, RecorderManager, and Player classes in the OpenTok JavaScript APIreference.

OpenTok JavaScript API Tutorials and Sample Code 42

Copyright 2012 TokBox, Inc. All rights reserved. 6/13/2012