Have you explored the newest version of the OpenTok platform? Check out OpenTok 2.0, built on top of WebRTC. Learn more

TB class

The first step in using the TokBox API is to call the TB.initSession() method. Other methods of TB object check for system requirements, initialize a DeviceManager object, and set up error logging.

Note that all of the methods of the TB class are static methods.

TB methods

The TB object includes the following static methods:

Method Description
TB.addEventListener(eventType:String, listener:Function) Registers a method as an event listener for a specific event.
TB.checkSystemRequirements():Number Checks the system for OpenTok API support. Returns 1 if the system supports the OpenTok API; 0 if it does not.
TB.initDeviceManager(apiKey:String):DeviceManager Initializes and returns a DeviceManager.
TB.initPublisher(apiKey:String [, replaceElementId:String, properties:PublisherProperties]):Publisher Initializes and returns a Publisher.
TB.initRecorderManager(apiKey:String):RecorderManager Initializes and returns a RecorderManager.
TB.initSession(sessionId:String):Session Initializes and returns the local session object for a specified session ID.
TB.log(message:String) Sends a string to the log output.
TB.removeEventListener(eventType:String, listener:Function) Removes an event listener for a specific event.
TB.reportIssue(description:String) Submits an issue report to TokBox.
TB.setLogLevel(logLevel:Number) Sets the API log level.
TB.upgradeSystemRequirements() Provides an interface for the user to update to the latest version of Flash Player.

TB.addEventListener(type:String, listener:Function)

Registers a method as an event listener for a specific event. The TB class can dispatch one type of event — an exception event. See TB events.

Parameters

type (String) — This string identifying the type of event. The TB object can only dispatch one type of event: an exception event. This event is defined by the ExceptionEvent class, and it is of type "exception". The ExceptionEvent object defines this event.

listener (Function) — The function to be invoked when the TB object dispatches the event.

Example

The following example registers a function, exceptionHandler() as the event handler for exception events.

TB.addEventListener("exception", exceptionHandler);

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

TB.checkSystemRequirements():Number

Checks if the system supports the OpenTok API.

Returns

Returns a number: 1 if the system supports the OpenTok API; 0 if it does not.

TB.initDeviceManager(apiKey:String):DeviceManager

Initializes and returns a DeviceManager object.

The OpenTok JavaScript library prompts the user to upgrade the version of Flash Player (if required) when you call this method. The OpenTok library now requires Adobe Flash 11.1 or higher. You can prevent this prompt from appearing by checking TB.checkSystemRequirements() before calling one of these methods.

Parameters

apiKey (String) — The API key that TokBox provided you when you signed up for an OpenTok account.

Returns

DeviceManager — A DeviceManager object, with which you can manage cameras and microphones for published streams.

See

DeviceManager

TB.initPublisher(apiKey:String [,replaceElementId:String, properties:PublisherProperties ]):Publisher

Initializes and returns a Publisher object. Before calling Session.publish(), you can use this Publisher object to test the microphone and camera attached to the Publisher. You can then pass this Publisher object to Session.publish() to publish a stream to a session.

If the OpenTok library does not have access to the camera or microphone, the Flash Player Settings dialog box is displayed. The Publisher object dispatches accessDialogOpened and accessDialogClosed events when the dialog box opens and closes. The Publisher object dispatches accessAllowed and accessDenied events when the user grants or denies access to the camera and microphone.

Note: If you intend to reuse a Publisher object created using TB.initPublisher() to publish to different sessions sequentially, call either Session.disconnect() or Session.unpublish(). Do not call both. Then call the preventDefault() method of the streamDestroyed or sessionDisconnected event object to prevent the Publisher object from being removed from the page.

The OpenTok JavaScript library prompts the user to upgrade the version of Flash Player (if required) when you call this method. The OpenTok library now requires Adobe Flash 11.1 or higher. You can prevent this prompt from appearing by checking TB.checkSystemRequirements() before calling one of these methods.

Parameters

apiKey (String) — The API key that TokBox provided you when you signed up for an OpenTok account.

replaceElementId (String) — The id attribute of the existing DOM element that the Publisher video replaces. If you do not specify a replaceElementId, the application appends a new DOM element to the HTML body. Note: Set the height and width properties of the properties parameter to set the dimensions of the publisher video; do not set the height and width of the container element (using CSS).

The application throws an error if an element with an ID set to the replaceElementId value does not exist in the HTML DOM.

properties (Object) — Optional. This is an optional object that contains the following properties (each of which are optional):

  • cameraName (String) — The name of a camera to use. You can obtain an array of Camera objects by calling the DeviceManager.detectDevices() method. The DeviceManager dispatches a devicesDetected event, which includes an array of Camera objects. Each Camera object has a name property. If you specify an invalid camera name, the Publisher object dispatches an invalidDeviceName event. The event is a DeviceEvent object, with the camera.name property set to the invalid name and the camera.status property set to "invalid".
  • encodedHeight (Number) — The desired height, in pixels, of the resolution of the encoded video stream. Specify a number from 1 to 640. Use this value, along with the encodedWidth property of the properties parameter, to set the desired encoded resolution of the video stream. If you do not specify a value, the height of the encoded video stream is 264 pixels. If the client's bandwidth does not support the desired encoding resolution, OpenTok will encode using the nearest supported resolution. When the actual encoded resolution is determined, the Session object dispatches a streamPropertyChanged event. The changedProperty property of the StreamPropertyChangedEvent object is set to "quality". The encodedHeight property of the newValue property of the event is set to the height of the resolution of the encoded video stream.

    The Publisher may adjust the camera resolution based on bandwidth considerations. When this adjustment is made, the image may skew slightly. Flash Player requires that the width and height of the camera be set to integers, and if the new values do not match the requested aspect ratio exactly, some skewing can result. For best results, use values for encodedWidth and encodedHeight that match a standard aspect ratio, such as 4:3.

    (Note: use the height property of the properties parameter to set the height of the Publisher video on the page.)
  • encodedWidth (Number) — The desired width, in pixels, of the resolution of the encoded video stream. Specify a number from 1 to 640. Use this value, along with the encodedHeight property of the properties parameter, to set the desired encoded resolution of the video stream. If you do not specify a value, the height of the encoded video stream is 198 pixels. If the client's bandwidth does not support the desired encoding resolution, OpenTok will encode using the nearest supported resolution. When the actual encoded resolution is determined, the Session object dispatches a streamPropertyChanged event. The changedProperty property of the StreamPropertyChangedEvent object is set to "quality". The encodedWidth property of the newValue property of the event is set to the width of the resolution of the encoded video stream.

    The Publisher may adjust the camera resolution based on bandwidth considerations. When this adjustment is made, the image may skew slightly. Flash Player requires that the width and height of the camera be set to integers, and if the new values do not match the requested aspect ratio exactly, some skewing can result. For best results, use values for encodedWidth and encodedHeight that match a standard aspect ratio, such as 4:3.

    (Note: use the width property of the properties parameter to set the width of the Publisher video on the page.)
  • height (Number) — The desired height, in pixels, of the displayed Publisher video stream (default: 198). Note: Use the height and width properties to set the dimensions of the publisher video; do not set the height and width of the container element (using CSS).
  • microphoneEnabled (Boolean) — Deprecated in OpenTok v0.91.9. Use the publishAudio property instead.
  • microphoneGain (Number) — The desired microphone gain, between 0 and 100, when the Publisher is first published (default: 50). After you publish the stream, you can adjust the microphone gain by calling the setMicrophoneGain() method of the Publisher object.
  • microphoneName (String) — The name of a microphone to use. You can obtain an array of Microphone objects by calling the DeviceManager.detectDevices() method. The DeviceManager dispatches a devicesDetected event, which includes an array of Microphone objects. Each Microphone object has a name property. If you specify an invalid microphone name, the Publisher object dispatches an invalidDeviceName event. The event is a DeviceEvent object, with the microphone.name property set to the invalid name and the microphone.status property set to "invalid".
  • mirror (Boolean) — Whether the publisher's video image is mirrored in the publisher's page. The default value is true (the video image is mirrored). This property does not affect the display on other subscribers' web pages .
  • name (String) — The name for this stream. The name appears at the bottom of Subscriber videos. The default value is "" (an empty string). Setting this to a string longer than 1000 characters results in an runtime exception.
  • publishAudio (Boolean) — Whether to initially publish audio for the stream (default: true). This setting applies when you pass the Publisher object in a call to the Session.publish() method. Note: Prior to calling the Session.publish() method, set the showMicSettings property of a DeviceManager object to false if you are publishing in video-only mode.
  • publishVideo (Boolean) — Whether to initially publish video for the stream (default: true). This setting applies when you pass the Publisher object in a call to the Session.publish() method. Note: Prior to calling the publish() method, set the showVideoSettings property of a DeviceManager object to false if you are publishing in audio-only mode.
  • rememberDeviceAccess (Boolean) — Whether to display a "Remember" option in the Flash Player Settings dialog box. The Flash Player Settings dialog box lets the user grant access to the camera and microphone for a website. When you set this property to true, the user's selection is remembered in subsequent sessions.
  • reportMicLevels (Boolean) — Whether the Session object will dispatch microphoneLevelChanged events for the Publisher's stream. (See the documentation for the microphoneLevelChanged event). The Session object for all clients connected clients will dispatch this event for the stream (if you set this property to true).
  • style (Object) — An object containing properties that define the initial appearance of some user interface controls of the Publisher. The style object includes the following properties:

    • backgroundImageURI (String) — A URI for an image to display as the background image when a video is not displayed. (A video may not be displayed if you call publisherVideo(false) on the Publisher object). You can pass an http or https URI to a PNG, JPEG, or non-animated GIF file location. You can also use the data URI scheme (instead of http or https) and pass in base-64-encrypted PNG data, such as that obtained from the Publisher.getImgData() method. For example, you could set the property to "data:VBORw0KGgoAA...", where the portion of the string after "data:" is the result of a call to Publisher.getImgData(). If the URL or the image data is invalid, the property is ignored (the attempt to set the image fails silently).
    • buttonDisplayMode (String) — How to display the microphone controls and settings button. Possible values are: "auto" (controls are displayed when the stream is first displayed and when the user mouses over the display), "off" (controls are not displayed), and "on" (controls are displayed). The showMicButton and showSettingsButton properties define whether each individual control is displayed.
    • nameDisplayMode (String) — Whether to display the stream name. Possible values are: "auto" (the name is displayed when the stream is first displayed and when the user mouses over the display), "off" (the name is not displayed), and "on" (the name is displayed).
    • showMicButton (Boolean) — Whether to display the microphone controls.
    • showSettingsButton (Boolean) — Whether to display the settings buttons.
  • width (Number) — The desired width, in pixels, of the displayed Publisher video stream (default: 264). Note: Use the height and width properties to set the dimensions of the publisher video; do not set the height and width of the container element (using CSS).
  • wmode (String) — Set this property to set the transparency of the SWF object used to display the stream. Possible values match the wmode values for the object and embed tags for a SWF file: "opaque", "transparent" (the default), or "window". (For more information, see Flash OBJECT and EMBED tag attributes (at adobe.com).

Returns

Publisher — A Publisher object.

See

Session.publish()

TB.initRecorderManager(apiKey:String):RecorderManager

Initializes and returns a RecorderManager object.

The OpenTok JavaScript library prompts the user to upgrade the version of Flash Player (if required) when you call this method. The OpenTok library now requires Adobe Flash 11.1 or higher. You can prevent this prompt from appearing by checking TB.checkSystemRequirements() before calling one of these methods.

Parameters

apiKey (String) — The API key that TokBox provided you when you signed up for an OpenTok account.

Returns

RecorderManager — A RecorderManager object, with which you can record and play back stand-alone archives.

See

RecorderManager

TB.initSession(sessionId:String):Session

Initializes and returns the local session object for a specified session ID.

You connect to the session using the connect() method of the Session object returned by the TB.initSession() method. Note that calling TB.initSession() does not initiate communications with the cloud. It simply initializes the Session object that you can use to connect (and to perform other operations once connected).

The OpenTok JavaScript library prompts the user to upgrade the version of Flash Player (if required) when you call this method. The OpenTok library now requires Adobe Flash 11.1 or higher. You can prevent this prompt from appearing by checking TB.checkSystemRequirements() before calling one of these methods.

For an example, see Session.connect().

Parameters

sessionId (String) — The session ID identifying the OpenTok session.

Returns

Session — The session object through which all further interactions with the session will occur.

TB.log(message:String)

Sends a string to the the debugger console (such as Firebug), if one exists. However, the function only logs to the console if you have set the log level to TB.LOG or TB.DEBUG, by calling TB.setLogLevel(TB.LOG) or TB.setLogLevel(TB.DEBUG).

Parameters

message (String) — The string to log.

TB.removeEventListener(type:String, listener:Function)

Removes an event listener for a specific event.

Parameters

type (String) — The string identifying the type of event.

listener (Function) — The event listener function to remove.

The TB object can only dispatch one type of event — an exception event.

The TB object throws an exception if the listener name is invalid.

TB.reportIssue(description:String)

Submits an issue report to TokBox. The issue is described in the description string. Upon successfully submitting an issue report to TokBox, the TB object dispatches an issueReported event, which is defined by the IssueReportedEvent class. The issueId property of the event is a unique 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 object dispatches an exception event. The code property of the event object is set to 2010.

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

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

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

Parameters

description (String) — The description of the issue you want to report.

Events

issueReported (IssueReportedEvent) — Dispatched when the issue is successfully reported to TokBox. The issueId property of the event object is the unique identifier for the issue.

exception (ExceptionEvent) — Dispatched if the issue cannot be sent to TokBox (for example, due to no network connection).

Example

This example shows how to report an issue using the TB.reportIssue() method:

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 report 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.
}

TB.setLogLevel(logLevel:String)

Sets the API log level.

Calling TB.setLogLevel() sets the log level for runtime log messages that are the OpenTok library generates. The default value for the log level is TB.ERROR.

The OpenTok JavaScript library displays log messages in the debugger console (such as Firebug), if one exists.

Parameters

logLevel (Number) — The degree of logging desired by the developer:

  • TB.NONE — API logging is disabled.
  • TB.ERROR — Logging of errors only.
  • TB.WARN — Logging of warnings and errors.
  • TB.INFO — Logging of other useful information, in addition to warnings and errors.
  • TB.DEBUG — Fine-grained logging of all API actions.

Example

The following example logs an error message in the <opentok_console> div element. The error is caused because the code attempts to publish a stream before the Session object dispatches a sessionConnected event.

<script>
    session = TB.initSession(sessionId);
    publisher = TB.initPublisher(API_KEY, "publishContainer");
    session.publish(publisher);
</script>

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

See

TB.log()

TB.upgradeSystemRequirements()

Provides an interface for the user to update to the latest version of Flash Player.

Examples

The following code alerts the user to upgrade if they do not have a version of Flash Player that supports OpenTok:

if (!TB.checkSystemRequirements()) {
    TB.upgradeSystemRequirements();
}

The following code alerts the user to upgrade if they do not have a version of Flash Player that supports publishing H.264, which is supported in Flash Player 11:

if (!swfobject.hasFlashPlayerVersion('11')) {
    TB.upgradeSystemRequirements();
}

(The swfobject.hasFlashPlayerVersion() method is included in the TB.js file.)

Once a client has connected to a session, you can check the session.capablities.publishH264 property to determine if the user can publish h.264 video. You can then notify the user to update if they do not have the supported Flash Player version:

var session = TB.initSession(SESSION_ID);
session.addEventListener("sessionConnected", sessionConnectedHandler);
session.connect(API_KEY, TOKEN);

function sessionConnectedHandler(event) {
    if (!session.capabilities.publishH264) {
        TB.upgradeSystemRequirements();
    }
}

TB events

The TB class can dispatch events of the following type:

Event type Event class Description
"exception" ExceptionEvent The app encounters an asynchronous exception.
"issueReported" IssueReportedEvent The call to TB.reportIssue() succeeded.

IRC Live Chat

Have a quick question? Chat with TokBox Support on IRC. Join chat