The Session object returned by the TB.initSession() method provides access to much of the OpenTok functionality.
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 the Session.forceUnpublish()
method. To call the Session.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 the
Archive.startPlayback() method or the RecorderManager.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.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.record If set to 1, the client can
record archives (by calling the RecorderManager.displayRecorder() method,
the Session.startRecording() method, or the Stream.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.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.
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 pass this value into the
TB.initSession() method when you create the Session object. (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()).
For more information on sessions and session IDs, see
Session creation.
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 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. |
| loadArchive(archiveId:String) | Loads the archive with the corresponding archive ID. |
|
publish(publisher:Publisher]):Publisher publish(replaceElementId:String [, properties:Object]):Publisher |
Publishes a stream to the session. |
| 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. |
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.
Closes local publishers and subscribers, removing their video displays from the local web page DOM.
Call the cleanup() method after calling the preventDefault() method of a sessionDisconnected event.
The default behavior of the event is to remove any local publishers and subscribers from the session. If you call the preventDefault()
method of a sessionDisconnected event, the default behavior is prevented. You can then, optionally, call the cleanup() method
of the Session object after (for example) cleaning up or adjusting related elements in the HTML 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:
publishers array of the Session object and calling the unpublish() method of the Session object for each Publisher object.
subscribers array of the Session object and calling the unsubscribe() method of the Session object for each Subscriber object.
Example
The following example calls the cleanup method in response to a sessionDisconnected event:
var apiKey = ""; // Replace with your API key. See https://dashboard.tokbox.com/projects
var sessionID = ""; // Replace with your own session ID.
// See https://dashboard.tokbox.com/projects
var session = TB.initSession(sessionID);
session.addEventListener("sessionDisconnected", sessionDisconnectHandler);
session.connect(apiKey, token);
function sessionDisconnectHandler(sessionDisconnectEvent) {
event.preventDefault();
// Do other things, such as remove and adjust other DOM elements
// before calling the following:
session.cleanup();
}
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.
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.
Connects to an OpenTok session. Pass your API key as the apiKey parameter. You get an API key when you
sign up for an OpenTok account. Pass a token string as the
token parameter. You generate a token using the
OpenTok server-side libraries or the
Dashboard page. For more information, see
Connection token creation.
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 signed up for an OpenTok account.
token (String) The session token. You generate a session token using the OpenTok server-side libraries or the Dashboard page. For more information, see Connection token creation.
properties (Object) (Optional) This object contains the following properties:
connectionData (String) Deprecated in OpenTok v0.91.59. When you generate a user token string pass the connection data string to the
generate_token() method of the
OpenTok
server-side libraries. You can also generate a token and define connection data on the
Dashboard page.
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.)
detectConnectionQuality (Number) A value of either 0 or 1, which determines
whether the connection.connectionQuality property of the Session object will be set (1)
or not (0). The connection.connectionQuality property 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.)connection.connectionQuality property of a Session object is only available once the
Session object dispatches the sessionConnected event. As an alternative, if you do not need
to know the connection quality before publishing, you can leave this property set to 0 (the default),
and check the quality property of the Stream object corresponding to a Stream the client
publishes (see Stream.quality property). However, you may want to have the
connection quality information before you publish a stream; in this case, set detectConnectionQuality
to 1 and check the the connection.connectionQuality property of the Session object once the
Session dispatches the sessionConnected event.
Events dispatched
exception (ExceptionEvent)
Dispatched by the TB class locally in the event of an error.
connectionCreated (ConnectionEvent)
Dispatched by the Session object on all clients connected to the session.
sessionConnected (SessionConnectEvent)
Dispatched locally by the Session object when the connection is established.
Example
The following code initializes a session and sets up an event listener for when the session connects:
var apiKey = ""; // Replace with your API key. See https://dashboard.tokbox.com/projects
var sessionID = ""; // Replace with your own session ID.
// See https://dashboard.tokbox.com/projects
var token = ""; // Replace with a generated token that has been assigned the moderator role.
// See https://dashboard.tokbox.com/projects
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
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.
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.
Parameters
apiKey (String) Your API key. You get an API key when you sign up for an OpenTok account.
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." |
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 on remote clients dispatch streamDestroyed events
for any stream you were publishing. The Session object dispatches a sessionDisconnected event locally.
The Session objects on remote clients 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
kets 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.
If the session is not currently connected, calling this method causes a warning to be logged. See TB.setLogLevel().
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. Be sure to call preventDefault() only
if the connection.connectionId property of the Stream object in the event matches the
connection.connectionId property of your Session object (to ensure that you are preventing
the default behavior for your published streams, not for other streams that you subscribe to).
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.
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 OpenTok
server-side libraries or the Dashboard page.
See ExceptionEvent and TB.addEventListener().
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 (event.code = 1530),
or the specified stream is not publishing to the session (event.code = 1535).
sessionDisconnected (SessionDisconnectEvent)
On the client which has the connection terminated.
streamDestroyed (StreamEvent)
If streams are stopped as a result of the connection ending.
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 libraries or the Dashboard page.
You pass the token string as a parameter of the connect() method of the Session object.
See ExceptionEvent and
TB.addEventListener().
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.
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.
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.
Returns
StateManager The StateManager object for the Session.
See
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.
Loads the Archive with the corresponding archive ID.
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." |
The publish() method starts publishing an audio-video stream to the session.
The audio-video stream is 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 clients dispatch the streamCreated event.
This method takes two forms:
publish(publisher:Publisher]) In this form, you pass a Publisher object
as the one parameter of the method. You can initialize a Publisher object by calling the
TB.initPublisher() method. Before calling Session.publish(),
you can use the Publisher object to set up and test the microphone and camera used by the Publisher.
The ability to create Publisher objects before calling the Session.publish() method was added
in OpenTok v0.91.57.
publish([replaceElementId:String, properties:Object]):Publisher In this form, you
do not pass a Publisher object into the function. Instead, you pass in a
replaceElementId (the ID of the DOM element that the Publisher will replace)
and a properties object that defines options for the Publisher. The method
returns a new Publisher object, which starts sending an audio-video stream to the session.
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 calling this method creates a new Publisher object and 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.
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
of the OpenTok
server-side libraries or the Dashboard page. You pass
the token string as a parameter of the connect() method of the Session object.
See ExceptionEvent and TB.addEventListener().
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) Optional. Pass in this parameter only if
you are not passing in a Publisher object to the Session.publish() method.
This parameter is the id attribute of the existing DOM element that the new
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.
Pass in this parameter only if you are not passing in a Publisher object to the
Session.publish() method. This is an optional object that contains properties
defining the publisher. For a description of these properties, see the description of the
properties parameter of the TB.initPublisher()
method.
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 apiKey = ""; // Replace with your API key. See https://dashboard.tokbox.com/projects
var sessionId = ""; // Replace with your own session ID.
// See https://dashboard.tokbox.com/projects
var token = ""; // Replace with a generated token that has been assigned the moderator role.
// See https://dashboard.tokbox.com/projects
var session = TB.initSession(sessionID);
session.addEventListener("sessionConnected", sessionConnectHandler);
session.connect(apiKey, token);
function sessionConnectHandler(event) {
var divProps = {width: 400, height:300, name:"Bob's stream"};
publisher = TB.initPublisher(API_KEY, 'publisher', divProps);
// This assumes that there is a DOM element with the ID 'publisher'.
session.publish(publisher);
}
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.
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.
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
Starts recording the session to the archive.
OpenTok archives are limited to 90 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
Stops recording the session.
OpenTok archives are limited to 90 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 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
Subscribes to a stream that is available to the session. You can get an array of
available streams from the streams property of the sessionConnected
and streamCreated events (see SessionConnectEvent and
StreamEvent).
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:
subscribeToAudio property instead.
setAudioVolume() method
of the Subscriber object. This volume setting affects local playback only; it does not
affect the stream's volume on other clients.
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 subscribeToVideo(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 the data URI 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 the Subscriber.getImgData() method. 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 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).true).
true).
wmode value
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
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 = ""; // Replace with your own session ID.
// See https://dashboard.tokbox.com/projects
var token = ""; // Replace with a generated token that has been assigned the moderator role.
// See https://dashboard.tokbox.com/projects
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);
}
}
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);
}
}
The unpublish() method ceases publishing the specified publisher's audio-video stream
to the session. By default, 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.
To prevent the Publisher from being removed from the DOM
, add an event listener for the streamDestroyed event
and call the preventDefault() method of the event object.
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. Be sure to call preventDefault() only
if the connection.connectionId property of the Stream object in the event matches the
connection.connectionId property of your Session object (to ensure that you are preventing
the default behavior for your published streams, not for other streams that you subscribe to).
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 = ""; // Replace with your own session ID.
// See https://dashboard.tokbox.com/projects
var token = ""; // Replace with a generated token that has been assigned the moderator role.
// See https://dashboard.tokbox.com/projects
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 = TB.initPublisher(API_KEY, 'publisher', divProps);
session.publish(publisher);
}
function unpublsh() {
session.unpublish(publisher);
}
</script>
<body>
<div id="publisherContainer/>
<br/>
<a href="javascript:unpublish()">Stop Publishing</a>
</body>
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 = ""; // Replace with your own session ID.
// See https://dashboard.tokbox.com/projects
var token = ""; // Replace with a generated token that has been assigned the moderator role.
// See https://dashboard.tokbox.com/projects
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
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.
|
"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. |