Session class
The Session object returned by the TB.initSession() method provides access to much of the OpenTok functionality. The Session object exposes functionality through properties, methods and event handlers.
Session properties
A Session object has the following properties:
capabilities (Capabilities) An object that includes information about the capabilities of the client. This object has the following properties:
forceUnpublish Specifies whether you can call theSession.forceUnpublish()method. To call theSession.forceUnpublish()method, the user must have a token that is assigned the role of moderator.playback If set to 1, the client can play back archives (by calling theArchive.startPlayback()method or theRecorderManager.displayPlayer()method). If set to 0, the client cannot play back archives. Currently, this property is set to 1 only if the client is assigned a token with a moderator role. Added in OpenTok v0.91.23.publish Specifies whether you can publish to the session (1) or not (0). The ability to publish is based on a few factors. To publish, the user must have a token that is assigned a role that supports publishing. There must be a connected camera and microphone. Also, the client environment must support publishing. (Currently, publishing is not supported when running in the browser on Android OS.)publishH264 Specifies whether you can publish h.264 video (true) or not (false). You should check this property if your app needs to support the OpenTok iOS SDK, which supports h.264 video only. Added in OpenTok v0.91.49.record If set to 1, the client can record archives (by calling theRecorderManager.displayRecorder()method, theSession.startRecording()method, or theStream.startRecording()method). If set to 0, the client cannot record archives. Currently, this property is set to 1 only if the client is assigned a token with a moderator role. Added in OpenTok v0.91.23.subscribe Specifies whether you can subscribe to streams in the session (1) or not (0). Currently, this capability is available for all users on all platforms.
For more information on token roles, see the generate_token() method of the OpenTok server-side libraries.
The capabilities property was added in OpenTok v0.91.12.
connection
(Connection)
The Connection object for this session.
The connection property is only available once the Session object dispatches the sessionConnected event.
The Session object asynchronously dispatches a sessionConnected event in response to a successful call to
connect() method. See: connect() and
Connection.
sessionId (String) The session ID for this session. You obtain a session ID as a return value when connecting to the OpenTok session creation URL. You obtain a session object by supplying the session ID to the TB.initSession() method. (Note: a Session object is not connected to the TokBox server until you call the connect() method of the object and the object dispatches a connected event. See TB.initSession() and connect()).
Note: Session properties should only be used as read-only entities. The results of using JavaScript to directly change the values of Session properties will be unpredictable.
Session methods
Session objects have the following methods:
| Method | Description |
|---|---|
| addEventListener(eventType:String, listener:Function) | Registers a method as an event listener for a specific event. |
| cleanup() | Closes local publishers and subscribers, removing their video displays from the local web page DOM. |
|
closeArchive(archive:Archive) |
Closes the specified archive. |
| connect(apiKey:String, token:String[, properties:Object]) | Connects to an OpenTok session. |
|
createArchive() |
Creates a new Archive object. |
| disconnect() | Disconnects from the OpenTok session. |
| forceDisconnect(connection:Connection) | Forces a session connection to leave the session. |
| forceUnpublish(stream:Stream) | Forces the publisher of the specified stream to stop publishing the stream. |
| getStateManager():StateManager | Returns the StateManager object for the session, with which you can set and obtain session state data. |
| getSubscribersForStream(stream:Stream):Array[Subscriber] | Returns the local Subscriber objects for a given stream. |
| getPublisherForStream(stream:Stream):Publisher | Returns the local Publisher object for a given stream. |
| publish(replaceElementId:String[, properties:Object]):Publisher | Publishes a stream to the session. |
|
loadArchive(archiveId:String) |
Loads the archive with the corresponding archive ID. |
| removeEventListener(type:String, listener:Function) | Removes an event listener for a specific event. |
|
startRecording(archive:Archive) |
Starts recording the session to an archive. |
|
stopRecording(archive:Archive) |
Stops recording the session to an archive. |
| signal() | Sends a signal to all connections in the session. |
| subscribe(stream:Stream, [replaceElementId:String, properties:Object]):Subscriber | Subscribes to a stream that is available to the session. |
| unpublish(publisher:Publisher) | Stops publishing a stream to the session. |
| unsubscribe(subscriber:Subscriber) | Stops subscribing to a stream in the session. |
addEventListener(type:String, listener:Function)
Registers a method as an event listener for a specific event. See Session events.
If a handler is not registered for an event, the event is ignored locally. If the JavaScript method does not exist, the event is ignored locally.
Throws an exception if the listener name is invalid.
Parameters
type (String) The string identifying the type of event. See TB events.
listener (Function) The function to be invoked when the Session object dispatches the event.
cleanup()
Closes local publishers and subscribers, removing their video displays from the local web page DOM.
Calling the cleanup() method stops all Publishers in the current session on the local web page from publishing, unsubscribes all Subscribers, and removes all associated displays from the local web page. Calling cleanup() method is equivalent to doing the following:
- Looping through the the
publishersarray of the Session object and calling theunpublish()method of the Session object for each Publisher object. - Looping through the the
subscribersarray of the Session object and calling theunsubscribe()method of the Session object for each Subscriber object.
You may call the cleanup() method in response to a sessionDisconnected event. In this case, the session has already been disconnected prior the call to the cleanup() method. Consequently, any local publishers and subscribers have already had their streams terminated. The cleanup() method simply removes their associated displays from the local web page. In this situation, calling the cleanup() method does not trigger a streamDestroyed event for any Publishers it cleans up. The Session object will have already dispatched this event as a result of the prior connection termination.
Events dispatched
streamDestroyed (StreamEvent) Dispatched when a
stream is destroyed as a result of the call to this method.
Example
The following example calls the cleanup method in response to a sessionDisconnected event:
var sessionID = "1690446fcddb5a4e6dd5ec1fcd1415312a18aae38";
apiKey = 1234;
var session = TB.initSession(sessionID);
session.addEventListener("sessionDisconnected", sessionDisconnectHandler);
session.connect(apiKey, token);
function sessionDisconnectHandler(sessionDisconnectEvent) {
session.cleanUp();
}
closeArchive(archive:Archive)
Closes the specified archive.
Closing an archive makes it available to be loaded and played back. It also lets you (or another moderator) create another archive for recording.
Added in OpenTok v0.91.23
Parameters
archive (Archive) The archive to close.
Events dispatched
archiveClosed (ArchiveEvent)
The archive is closed successfully. The first element of the archives property
of the event object is the Archive object that was closed.
connect(apiKey:String, token:String [, properties:Object])
Connects to an OpenTok session. Pass the API key as the apiKey parameter. You obtain a API key when you register with TokBox. Pass the token string as the token parameter.
Before calling this method, obtain a Session object by calling the TB.initSession(), which creates a session object based on a session ID.
Upon a successful connection, the Session object dispatches a sessionConnected event. Call the addEventListener() method to set up an event listener to process this event before calling other methods of the Session object.
The Session object dispatches a connectionCreated event when other clients create connections to the session.
Calling this method creates a hidden controller object on the web page. The controller has no visual manifestation to the end user, so no explicit placement control is provided for it.
The TB object dispatches an exception event if the session ID,
API key, or token string are invalid. See ExceptionEvent
and TB.addEventListener().
The application throws an error if the system requirements are not met (see TB.checkSystemRequirements()). The application also throws an error if the session has peer-to-peer streaming enabled and two clients are already connected to the session (see the OpenTok server-side libraries reference).
Parameters
apiKey (String) The API key that TokBox provided you when you registered for the OpenTok API.
token (String) The session token.
You generate a session token by connecting to the TokBox server using the
OpenTok server-side libraries. While using the staging environment, you can use
the 'devtoken' or 'moderator_token' test token strings token
in place of a proper server-generated token. Use the 'devtoken' test
string to assign the role of a publisher. Use the 'moderator_token'
test token string to assign the role of a moderator. (The 'moderator_token'
string was added in OpenTok v0.91.5.) For more information, see
Connection token creation,
Moving from testing to production,
and OpenTok server-side libraries reference.
properties (Object) (Optional) This object contains the following properties:
-
connectionData(String) A string containing metadata describing the connection. For example, you can pass the user ID, name, or other data describing the connection. Set this string only when testing with the staging environment and using a test token string (such as'devtoken') as thetokenparameter value. The length of the string is limited to 1000 characters. detectConnectionQuality(Number) A value of either 0 or 1, which determines whether theconnectionQualityproperty of theconnectionproperty of the Session object will be set (1) or not (0). TheconnectionQualityproperty of theconnectionproperty of the Session object includes information about the downstream bandwidth, the upstream bandwidth, and the latency at the time of the connection. (See the connection property.)
Important: When you generate a user token string (as in the production environment),
pass the connection data string to the generateToken() method of the
OpenTok server-side library.
Passing the data on the server prevents a client from sending data insecurely. The
connectionData string passed to the client-side Session.connect() method
is ignored.
The data property of the Connection object is set to
the connection data string.
Clients can access the Connection object in event listeners for the sessionConnected event,
the connectionCreated event, and the streamCreated event. The sessionCreated
and connectionCreated events each have a connections property, which is an array of
Connection objects. The sessionCreated and streamCreated events each have
a streams property, which is an array of Stream objects. (Each Stream object has a
connection property, which is a Connection object.)
Added in OpenTok v0.91.20.
Events dispatched
exception (ExceptionEvent)
Dispatched locally in the event of an error.
connectionCreated (ConnectionEvent)
Dispatched on other clients.
sessionConnected (SessionConnectEvent)
Dispatched locally when the connection is established.
Example
The following code initializes a session and sets up an event listener for when the session connects:
var sessionID = "123456789abcdef0123456789abcdef012345678"; // replace with your session ID
var apiKey = 1234; // replace with your API key
var token = "devtoken"; // replace with your connection token
var session = TB.initSession(sessionID);
session.addEventListener("sessionConnected", sessionConnectHandler);
session.connect(apiKey, token);
function sessionConnectHandler(sessionConnectEvent) {
//
}
The event listener for the sessionConnect event can process the SessionConnectEvent object. (In this example, the sessionConnectHandler() function is the event listener.) For instance, it can loop through the array of the current streams in the session and present them on the page.
See
createArchive(apiKey:String, type:String, title:String)
Creates a new Archive object. You can use this new Archive object to record. You record a session or individual streams, based on the archive type that you specify.
You can create and record only one archive at a time in a session. Check the length of the archives
property of the sessionConnected event. If it is 1, then an archive has already been created for the session
(and it has not been closes). Also, add event listeners for the archiveCreated and archiveClosed
events.
When using the OpenTok staging environment, archives are limited to 5 minutes in length. Archives in the staging environment are deleted after 3 days.
Note: The OpenTok archiving API also includes a stand-alone archive feature. This lets you record a video outside of an OpenTok session. Use the Recorder class to record stand-alone archives.
Added in OpenTok v0.91.23
Parameters
apiKey (String) Your API key.
type (String) The type of archive to create.
"perSession" Defines an archive that records all streams in a session."perStream" Defines an archive that can be used to record selected streams in a session.
title (String)
The title for the archive (such as "Recording D Nov. 22").
This parameter is optional.
Events dispatched
archiveCreated (ArchiveEvent) The
archive is created successfully. The first element of the archives
property of the event object is the Archive object that was created. Note that
you should store a record of the archive IDs of archives you create, so that
you can reference them later when loading the archive for playback.
exception (ArchiveEvent) The
OpenTok library could not load the archive. The TB object dispatches this
event. The event object includes these properties:
code |
title |
message |
3001 |
"Archive create
exception" |
"There was an error in creating the archive you requested." |
disconnect()
Disconnects from the OpenTok session.
Calling the disconnect() method ends your connection with the session. In the course of terminating your connection, it also ceases publishing any stream(s) you were publishing.
Session objects dispatch streamDestroyed events to all session connections for any stream you were publishing. The Session object dispatches a sessionDisconnected event locally. The Session objects on other (non-local) pages, dispatch connectionDestroyed events, letting other connections know you have left the session. The SessionDisconnectEvent and StreamEvent objects that define the sessionDisconnect and connectionDestroyed events each have a reason property. The reason property lets the developer determine whether the connection is being terminated voluntarily and whether any streams are being destroyed as a byproduct of the underlying connection's voluntary destruction.
Note that while calling the disconnect() method ceases publishing and subscribing to streams, it does not remove Publisher and Subscriber objects from the local web page. Call the cleanup() method in conjunction with the disconnect() method to create a smooth user experience when disconnecting.
If the session is not currently connected, calling this method causes a warning to be logged. See TB.setLogLevel().
Events dispatched
sessionDisconnected (SessionDisconnectEvent)
Dispatched locally when the connection is disconnected.
connectionDestroyed (ConnectionEvent)
Dispatched on other connections, along with the streamDestroyed event (as warranted).
streamDestroyed (StreamEvent)
Dispatched if streams are lost as a result of the session disconnecting.
forceDisconnect(connection:Connection)
Forces a remote connection to leave the session.
The forceDisconnect() method is normally used as a moderation tool
to remove users from an ongoing session.
When a connection is terminated using the forceDisconnect(),
sessionDisconnected, connectionDestroyed and
streamDestroyed events are dispatched in the same way as they
would be if the connection had terminated itself using the disconnect() method.
However,the reason property of a ConnectionEvent or StreamEvent object specifies
"forceDisconnected" as the reason for the destruction of the connection and stream(s).
While you can use the forceDisconnect() method to terminate your own connection,
calling the disconnect() method is simpler.
The TB object dispatches an exception event if the user's role
does not include permissions required to force other users to disconnect.
You define a user's role when you create the user token using the generate_token()
method using the OpenTok server-side SDKs. You pass the token string as a parameter of
the connect() method of the Session object. (In the test sandbox, you can also use the
"moderator_token" test token string, which puts the user in the moderator role.)
See ExceptionEvent,
TB.addEventListener(), and the
OpenTok server-side libraries reference.
The application throws an error if the session is not connected.
Parameters
connection (Object) The connection to be disconnected from the session.
This value can either be a Connection object or a connection ID (which can be
obtained from the connectionId property of the Connection object).
Events dispatched
connectionDestroyed (ConnectionEvent)
On clients other than which had the connection terminated.
exception (ExceptionEvent)
The user's role does not allow forcing other user's to disconnect.
sessionDisconnected (SessionDisconnectEvent)
On the client which has the connection terminated.
streamDestroyed (StreamEvent)
If streams are stopped as a result of the connection ending.
forceUnpublish(stream:Stream)
Forces the publisher of the specified stream to stop publishing the stream.
Calling this method causes the Session object to dispatch a streamDestroyed
event on all clients that are subscribed to the stream (including the client that is
publishing the stream). The reason property of the StreamEvent object is
set to "forceUnpublished".
The TB object dispatches an exception event if the user's role
does not include permissions required to force other users to unpublish.
You define a user's role when you create the user token using the generate_token()
method using the OpenTok server-side SDKs. You pass the token string as a parameter of
the connect() method of the Session object. (In the test sandbox, you can also use the
"moderator_token" test token string, which puts the user in the moderator role.)
See ExceptionEvent,
TB.addEventListener(), and the
OpenTok server-side libraries reference.
Parameters
stream (Stream) The stream to be unpublished.
Events dispatched
exception (ExceptionEvent)
The user's role does not allow forcing other users to unpublish.
streamDestroyed (StreamEvent)
The stream has been unpublished. The Session object dispatches this on all clients
subscribed to the stream, as well as on the publisher's client.
getPublisherForStream():Publisher
Returns the local Publisher object for a given stream.
When the Session object dispatches a streamDestroyed event that has
its reason property set to "forceUnpublished", calling the
preventDefault() method of the StreamEvent object prevents
a Publisher object from being unpublished automatically. You can then, optionally,
clean up the Publisher object yourself. You can call the
the getPublisherForStream() method to get the Publisher object
for which the stream pertains and call the unpublish() method.
Parameters
stream (Stream) The stream for which you want to find the Publisher.
Returns
Publisher A Publisher object
for the specified stream. Returns null if there is no local Publisher object for the
stream.
getStateManager():StateManager
Returns the StateManager object for the Session. For an example, see the example in the StateManager documentation.
Note: The Session State API is in beta testing. We welcome your comments.
Added in OpenTok v0.91.40.
Returns
StateManager The StateManager object for the Session.
See
getSubscribersForStream():Array[Subscriber]
Returns an array of local Subscriber objects for a given stream.
When the Session object dispatches a streamDestroyed event, you can
call the preventDefault() method of the StreamEvent object to prevent
Subscriber objects from being unsubscribed automatically. You can then, optionally,
clean up Subscriber objects yourself. You can call the
getSubscribersForStream() method to list the Subscriber objects
for which you will call the unsubscribe() method.
In most cases, the array returned will only contain a single Subscriber object. However, if for some reason the local web page has subscribed more than once to the same stream, all relevant Subscriber objects will be returned. If the stream is not subscribed to on the local page, an empty array will be returned.
Parameters
stream (Stream) The stream for which you want to find subscribers.
Returns
Array[Subscriber] An array of Subscriber objects for the specified stream.
loadArchive(archiveID:String)
Loads the Archive with the corresponding archive ID. Added in OpenTok v0.91.23.
Note: You should maintain records of the archive IDs of created archives. For example, you may want to save archive IDs in a server-side database.
Parameters
archiveId (String) The archive ID of the archive to be loaded.
Events dispatched
archiveLoaded (ArchiveEvent) The
archive is loaded successfully. The first element of the archives
property of the event object is the loaded Archive object. Dispatched by the
Session object.
exception (ExceptionEvent) The
OpenTok library could not load the archive. The TB object dispatches this
event. The code and title properties of the event object can
be set to the following:
code |
title |
message |
3000 |
"Archive load exception" |
"There was an error in loading the archive you specified." |
3006 |
"Archive load exception" |
"The archive you are trying to load does not exist." |
publish([replaceElementId:String, properties:Object]):Publisher
The publish() method starts publishing an audio-video stream to the session.
The audio-video stream is generally captured from a local microphone and webcam, depending
on how camera and microphone acquisition have been configured. Upon successful publishing,
the Session objects on all connected web pages
dispatch streamCreated.
A local display of the published stream is created on the web page by replacing the specified element in the DOM with a streaming video display. The video stream is automatically mirrored horizontally so that users see themselves and movement in their stream in a natural way. If the width and height of the display do not match the 4:3 aspect ratio of the video signal, the video stream is cropped to fit the display.
If the OpenTok API does not have access to the camera or microphone, the Flash Player Settings dialog box may display immediately upon publishing the stream.
The TB object dispatches an exception event if the user's role does not
include permissions required to publish. For example, if the user's role is set to subscriber,
then they cannot publish. You define a user's role when you create the user token using the
generate_token() method using the OpenTok server-side SDKs. You pass the token string as
a parameter of the connect() method of the Session object. (In the test sandbox, you can also use the
"moderator_token" test token string, which puts the user in the moderator role.)
See ExceptionEvent, TB.addEventListener(),
and the OpenTok server-side libraries reference.
The application throws an error if the session is not connected or if the
replaceElementId does not exist in the HTML DOM.
Parameters
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).
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 adevicesDetectedevent, which includes an array of Camera objects. Each Camera object has anameproperty. If you specify an invalid camera name, the Publisher object dispatches aninvalidDeviceNameevent. The event is a DeviceEvent object, with thecamera.nameproperty set to the invalid name and thecamera.statusproperty 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
encodedWidthproperty of thepropertiesparameter, 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 astreamPropertyChangedevent. ThechangedPropertyproperty of the StreamPropertyChangedEvent object is set to"quality". TheencodedHeightproperty of thenewValueproperty of the event is set to the height of the resolution of the encoded video stream. (Note: use theheightproperty of thepropertiesparameter to set the height of the Publisher video on the page.) Added in OpenTok v0.91.35. -
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
encodedHeightproperty of thepropertiesparameter, 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 astreamPropertyChangedevent. ThechangedPropertyproperty of the StreamPropertyChangedEvent object is set to"quality". TheencodedWidthproperty of thenewValueproperty of the event is set to the width of the resolution of the encoded video stream. (Note: use thewidthproperty of thepropertiesparameter to set the width of the Publisher video on the page.) Added in OpenTok v0.91.35. -
height (Number) The desired height, in pixels, of the
displayed Publisher video stream (default: 198). Note: Use the
heightandwidthproperties 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
publishAudioproperty 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. Added in OpenTok v0.91.19. -
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 adevicesDetectedevent, which includes an array of Microphone objects. Each Microphone object has anameproperty. If you specify an invalid microphone name, the Publisher object dispatches aninvalidDeviceNameevent. The event is a DeviceEvent object, with themicrophone.nameproperty set to the invalid name and themicrophone.statusproperty 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). Added in OpenTok v0.91.9. Note: Prior to calling thepublsh()method, set theshowMicSettingsproperty of a DeviceManager object tofalseif you are publishing in video-only mode. -
publishVideo (Boolean) Whether to initially publish video
for the stream (default:
true). Added in OpenTok v0.91.9. Note: Prior to calling thepublsh()method, set theshowVideoSettingsproperty of a DeviceManager object tofalseif you are publishing in audio-only mode. -
reportMicLevels (Boolean) Whether the Session object will dispatch
microphoneLevelChangedevents 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 totrue). Added in OpenTok v0.91.51. -
style (Object) An object containing properties that define the initial
appearance of some user interface controls of the Publisher. Added in OpenTok v0.91.19.
The
styleobject 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 callpublisherVideo(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 thedataURI 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 toPublisher.getImgData(). If the URL or the image data is invalid, the property is ignored (the attempt to set the image fails silently). Added in OpenTok v0.91.33.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). TheshowMicButtonandshowSettingsButtonproperties 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
heightandwidthproperties 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
wmodevalues for theobjectandembedtags 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 The Publisher object for this stream.
Events dispatched
exception (ExceptionEvent)
The user's role does not allow publishing.
streamCreated (StreamEvent)
The stream has been published. The Session object dispatches this on all clients
subscribed to the stream, as well as on the publisher's client.
Example
The following example publishes a video once the session connects:
var sessionID = "1690446fcddb5a4e6dd5ec1fcd1415312a18aae38";
var apiKey = 4444;
var token = "Replace with the TokBox token string provided to you."
var session = TB.initSession(sessionID);
session.addEventListener("sessionConnected", sessionConnectHandler);
session.connect(apiKey, token);
function sessionConnectHandler(event) {
var div = document.createElement('div');
div.setAttribute('id', 'publisher');
var publisherContainer = document.getElementById('publisherContainer');
publisherContainer.appendChild(div);
var divProps = {width: 400, height:300, name:"Bob's stream"};
publisher = session.publish('publisher', divProps);
}
removeEventListener(type:String, listener:Function)
Removes an event listener for a specific event.
Throws an exception if the listener name is invalid.
Parameters
type (String) The string identifying the type of event.
listener (Function) The event listener function to remove.
signal()
Sends a signal to all connections in the session.
Calling the signal() method causes the Session object on each
connected client to dispatch a signalReceived event. The
fromConnection property identifies the connection that originated
the signal. Clients can take whatever action is appropriate in response to the signal.
Because the signal carries no data payload, in most cases the receiving connection will poll the developer's webserver for additional information to determine what action to take.
Note that the Session object that calls the signal() method also
dispatches the signalReceived event locally (when it receives its own
signal back from the server).
The TB object dispatches an exception event if the user's role does not
include permissions required to signal. For example, if the user's role is set to subscriber,
then they cannot signal. You define a user's role when you create the user token using the
generate_token() method using the OpenTok server-side SDKs. Defining roles
for tokens was added in OpenTok v0.91.5. See ExceptionEvent,
TB.addEventListener(), and the
OpenTok server-side libraries reference.
The application throws an error if the session is not connected.
Events dispatched
exception (ExceptionEvent)
The user's role does not permit signalling.
signalReceived (SignalEvent)
The signal is received. (Dispatched on all subscribing clients.)
See
startRecording(archive:Archive)
Starts recording the session to the archive. Added in OpenTok v0.91.23
OpenTok archives are limited to 90 minutes in length. When using the OpenTok staging environment,
archives are limited to 5 minutes in length. After an archive reaches the time limit, the system
automatically stops recording, closes and saves the archive; and the Session object dispatches
an archiveClosed event (see Session events).
Parameters
archive (Archive) The archive to record to.
Events dispatched
exception (ExceptionEvent) The
OpenTok library could not load the archive. The TB object dispatches this
event. The code and title properties of the event object
can be set to the following:
code
|
title
|
message
|
1540
|
"Unable to record archive"
|
"This
token does not allow recording."
|
3004
|
"Record start exception"
|
"An error occurred when starting recording"
|
3007
|
"Session recording in
progress"
|
"This token does not allow recording. The role must be at least 'moderator'."
|
sessionRecordingStarted (Event) The
session has started archiving.
Errors thrown
The application throws an error if the archive is a loaded archive (used for playback), rather than a created archive (used for recording).
An error is also thrown if the archive type is not "perSession".
See
stopRecording(archive:Archive)
Stops recording the session. Added in OpenTok v0.91.23.
OpenTok archives are limited to 90 minutes in length. When using the OpenTok staging environment,
archives are limited to 5 minutes in length. After an archive the time limit, the system automatically
stops recording, closes, and saves the archive; and the Session object dispatches an
archiveClosed event (see Session events).
Parameters
archive (Archive) The archive to stop recording to.
Events dispatched
exception (ExceptionEvent) The
OpenTok library could not load the archive. The TB object dispatches this
event. The event object includes these properties:
sessionNotRecording (Event)
The stream is not currently being recorded. (Calling this method has no effect.)
The first element of the streams property of the StreamEvent object
is the Stream object representing the stream object. The Session object dispatches this event.
code
|
title
|
message
|
3005
|
"Record stop exception"
|
"An error occurred when stopping recording."
|
sessionRecordingStopped (Event) The
session has stopped archiving.
Errors thrown
The application throws an error if the archive is a loaded archive (used for playback), rather than a created archive (used for recording).
An error is also thrown if the archive type is not "perSession".
See
subscribe(stream:Stream, [replaceElementId:String, properties:Object])
Subscribes to a stream that is available to the session. You can get an array of
available streams from the streams of the sessionConnect event object.
The Session object dispatches this event in response to a successful call to the
connect() method. As other publishers connect to the session, the Session object
dispatches a streamCreated event. This event object has a streams
property, which is an updated array of the Stream objects corresponding to streams connected
to the session.
Starts subscribing to the session's audio-video stream specified.
The subscribed stream is displayed on the local web page by replacing the specified element in the DOM with a streaming video display. If the width and height of the display do not match the 4:3 aspect ratio of the video signal, the video stream is cropped to fit the display. If the stream lacks a video component, a blank screen with an audio indicator is displayed in place of the video stream.
The application throws an error if the session is not connected or if the
replaceElementId does not exist in the HTML DOM.
Parameters
stream (Stream) Stream object representing the stream to which we are trying to subscribe.
replaceElementId (String) String ID of the existing DOM element
that the Subscriber replaces. If you do not specify a replaceElementId, the application
appends a new DOM element to the HTML body.
properties (Object). This is an optional object that contains the following properties:
-
audioEnabled (Boolean) Deprecated in OpenTok v0.91.9.
Use the
subscribeToAudioproperty instead. -
audioVolume (Number) The desired audio volume, between 0
and 100, when the Subscriber is first opened (default: 50). After you subscribe to the
stream, you can adjust the volume by calling the
setAudioVolume()method of the Subscriber object. This volume setting affects local playback only; it does not affect the stream's volume on other clients. Added in OpenTok v0.91.19. - height (Number) The desired height, in pixels, of the displayed Subscriber video stream (default: 198).
-
style (Object) An object containing properties that define the initial
appearance of some user interface controls of the Subscriber. Added in OpenTok v0.91.19.
The
styleobject 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 callsubscribeToVideo(false)on the Subscriber object, or if the publisher does not publish video). You can pass an http or https URI to a PNG, JPEG, or non-animated GIF file location. You can also use thedataURI scheme (instead of http or https) and pass in base-64-encrypted PNG data, such as that obtained from the Subscriber.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 theSubscriber.getImgData()method. If the URL or the image data is invalid, the property is ignored (the attempt to set the image fails silently). Added in OpenTok v0.91.33.buttonDisplayMode(String) How to display the speaker controls. 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).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).
-
subscribeToAudio (Boolean) Whether to initially subscribe to audio
(if available) for the stream (default:
true). Added in OpenTok v0.91.9. -
subscribeToVideo (Boolean) Whether to initially subscribe to video
(if available) for the stream (default:
true). Added in OpenTok v0.91.9. - width (Number) The desired width, in pixels, of the displayed Subscriber video stream (default: 264).
-
wmode (String) Set this property to set the transparency of
the SWF object used to display the stream. Possible values match the
wmodevalue for theobjectandembedtags for a SWF file:"opaque","transparent"(the default), or"window". (For more information, see Flash OBJECT and EMBED tag attributes (at adobe.com).
Returns
Subscriber The Subscriber object for this stream. Stream control functions are exposed through the Subscriber object.
Example
The following code subscribes to available streams at the time that a session is connected
var sessionID = "1690446fcddb5a4e6dd5ec1fcd1415312a18aae38";
apiKey = 1234;
var streams = [];
var session = TB.initSession(sessionID);
session.addEventListener("sessionConnected", sessionConnectHandler);
session.connect(apiKey, token);
function sessionConnectHandler(event) {
for (var i = 0; i < event.streams.length; i++) {
var stream = event.streams[i];
displayStream(stream);
}
streams = event.streams;
}
function displayStream(stream) {
var div = document.createElement('div');
div.setAttribute('id', 'stream' + stream.streamId);
var streamsContainer = document.getElementById('streamsContainer');
streamsContainer.appendChild(div);
var divProps = {width: 400, height:300};
subscriber = session.subscribe(stream, 'stream' + stream.streamId, divProps);
}
You can also add an event listener for the streamCreated event. The Session object dispatches this event when a new stream is created.
session.addEventListener("streamCreated", streamCreatedHandler);
function streamCreatedHandler(event) {
for (var i = 0; i < event.streams.length; i++) {
var stream = event.streams[i];
displayStream(stream);
streams.push(stream);
}
}
unpublish(publisher:Publisher)
The unpublish() method ceases publishing the specified publisher's audio-video stream
to the session. The local representation of the audio-video stream is removed from the
web page. Upon successful termination, the Session object on every connected
web page dispatches
a streamDestroyed event.
Parameters
publisher (Publisher) The Publisher object to stop streaming.
Events dispatched
streamDestroyed (StreamEvent)
The stream associated with the Publisher has been destroyed. Dispatched on
the Publisher's browser and on the browser for all connections subscribing
to the publisher's stream.
Example
The following example publishes a stream to a session and adds a Disconnect link to the web page. Clicking this link causes the stream to stop being published.
<script>
var sessionID = "1690446fcddb5a4e6dd5ec1fcd1415312a18aae38";
var apiKey = 4444;
var token = "Replace with the TokBox token string provided to you."
var session = TB.initSession(sessionID);
session.addEventListener("sessionConnected", sessionConnectHandler);
session.connect(apiKey, token);
var publisher;
function sessionConnectHandler(event) {
var div = document.createElement('div');
div.setAttribute('id', 'publisher');
var publisherContainer = document.getElementById('publisherContainer');
publisherContainer.appendChild(div);
var divProps = {width: 400, height:300, name:"Bob's stream"};
publisher = session.publish('publisher', divProps);
}
function unpublsh() {
session.unpublish(publisher);
}
</script>
<body>
<div id="publisherContainer/>
<br/>
<a href="javascript:unpublish()">Disconnect</a>
</body>
unsubscribe(subscriber:Subscriber)
Stops subscribing to a stream in the session. The display of the audio-video stream is removed from the local web page.
Parameters
subscriber (Subscriber) The Subscriber object to unsubcribe.
Example
The following code subscribes to available streams at the time that a session is connected. For each stream, the code also adds an Unsubscribe link.
var sessionID = "1690446fcddb5a4e6dd5ec1fcd1415312a18aae38";
apiKey = 1234;
var streams = [];
var session = TB.initSession(sessionID);
session.addEventListener("sessionConnected", sessionConnectHandler);
session.connect(apiKey, token);
function sessionConnectHandler(event) {
for (var i = 0; i < event.streams.length; i++) {
var stream = event.streams[i];
var div = document.createElement('div');
div.setAttribute('id', 'stream' + stream.streamId);
var aLink = document.createElement('a');
aLink.setAttribute('href', 'javascript: unsubscribe(' + stream.streamId + ')');
aLink.innerHTML = "Unsubscribe";
var streamsContainer = document.getElementById('streamsContainer');
streamsContainer.appendChild(div);
streamsContainer.appendChild(aLink);
var divProps = {width: 400, height:300};
var subscriber = session.subscribe(stream, 'stream' + stream.streamId, divProps);
streams = event.streams;
}
}
function unsubscribe(streamId) {
for (var i = 0; i < streams.length; i++) {
var stream = streams[i];
if (stream.streamId == streamId) {
session.unsubscribe(stream);
}
}
}
See
Session events
A Session object can dispatch events of the following types:
| Event type | Event class | Description |
|---|---|---|
"archiveClosed"
|
ArchiveEvent |
The archive is closed successfully. The first element of the archives
property of the event object is the Archive object that was closed.
|
"archiveCreated"
|
ArchiveEvent |
The archive is created successfully. The first element of the archives
property of the event object is the Archive object that was created.
|
"archiveLoaded"
|
ArchiveEvent |
The archive is loaded successfully. The first element of the archives
property of the event object is the loaded Archive object.
|
"connectionCreated"
|
ConnectionEvent | A new connection to this session has been created. For a code example and more details, see ConnectionEvent. |
"connectionDestroyed"
|
ConnectionEvent | A connection to this session has ended. For a code example and more details, see ConnectionEvent. |
"microphoneLevelChanged"
|
VolumeEvent |
Indicates the new microphone activity level of one of the streams the client has subscribed to.
The streamId property of the event object is the stream ID for the stream. The
volume property of the event object is the current activity level (from 0 to 10) of the
microphone. The Session object dispatches this event for each stream to which the client has subscribed.
However, the publisher of the stream must set the reportMicLevels property of the
properties parameter when calling the Session.publish() method.
For more information, see VolumeEvent.
Added in OpenTok v0.91.41.
|
"sessionConnected"
|
SessionConnectEvent |
The page has connected to a session on the TokBox server. This event is dispatched asynchronously in response to a successful call to the connect() method of a session object. Before calling the connect() method, initialize the session by calling the TB.initSession() method. For a code example and more details, see SessionConnectEvent.
|
"sessionDisconnected"
|
SessionDisconnectEvent |
The session has disconnected. This event may be dispatched asynchronously in response to a successful call to the disconnect() method of the session object. The event may also be disptached if a session connection is lost inadvertantly, as in the case of a lost network connection. For a code example and more details, see SessionDisconnectEvent.
|
"sessionNotRecording"
|
Event |
The session is not being recorded. Calling
Session.stopRecording() has no effect.
|
"sessionRecordingInProgress"
|
Event |
The session is already being recorded. Calling
Session.startRecording() has no effect.
|
"sessionRecordingStarted"
|
Event | The session has started archiving. |
"sessionRecordingStopped"
|
Event | The session has stopped archiving. |
"signalReceived"
|
SignalEvent | A signal has been received. For a code example and more details, see SignalEvent. |
"streamCreated"
|
StreamEvent | A new stream has been created on this session. For a code example and more details, see StreamEvent. |
"streamDestroyed"
|
StreamEvent | A stream has closed on this connection. For a code example and more details, see StreamEvent. |
"streamPropertyChanged"
|
StreamPropertyChangedEvent |
A stream has started or stopped publishing audio or video (see
Publisher.publishAudio() and
Publisher.publishVideo());
or the quality property of the stream has been set (see Session.publish()).
|
"streamNotRecording"
|
StreamEvent |
The stream is not being recorded. Calling
Stream.stopRecording() has no effect.
|
"streamRecordingInProgress"
|
Event |
The stream is already being recorded to the specified archive. Calling
Stream.startRecording() has no effect.
|
"streamRecordingStarted"
|
StreamEvent | The stream has started being recorded to an archive. |
"streamRecordingStopped"
|
StreamEvent | The stream has stopped being recorded to an archive. |
IRC Live Chat
Have a quick question? Chat with other developers. Join chat
TokBox staff may not be online right now. To reach them during off-hours, visit the forums.