OT.initSession()
method provides access to much of the OpenTok functionality.
Properties
Name | Type | Description |
---|---|---|
capabilities |
Capabilities |
A
Capabilities
object that includes information about the capabilities of
the client. All properties of the
capabilities
object are undefined until you have connected to a session
and the completion handler for the
Session.connect()
method has been called without error.
|
connection |
Connection |
The
Connection
object for this session. The connection property is only
available once the completion handler for the
Session.connect()
method has been called successfully. See the
Session.connect()
method and the
Connection
class.
|
sessionId |
String |
The session ID for this session. You pass this value into
the
OT.initSession()
method when you create the Session object. (Note: a Session
object is not connected to the OpenTok server until you call
the connect() method of the object and its completion
handler is called without error. See the
OT.initSession()
and the
Session.connect()
methods.) For more information on sessions and session IDs,
see
Session creation
.
|
Methods
Name | Description |
---|---|
addEventListener
(type, listener, context)
|
Deprecated. |
connect
(token, completionHandler)
|
Connects to an OpenTok session. |
disableForceMute
()
→ {Promise}
|
Disables the active mute state of the session. |
disconnect
()
|
Disconnects from the OpenTok session. |
forceDisconnect
(connection, completionHandler)
|
Forces a remote connection to leave the session. |
forceMuteAll
(excludedStreams)
→ {Promise}
|
Forces all publishers in the session (except for those publishing excluded streams) to mute audio. |
forceMuteStream
(stream)
→ {Promise}
|
Forces a the publisher of a specified stream to mute its audio. |
forceUnpublish
(stream, completionHandler)
|
Forces the publisher of the specified stream to stop publishing the stream. |
getPublisherForStream
(stream)
→ {
Publisher
}
|
Returns the local Publisher object for a given stream. |
getSubscribersForStream
(stream)
→ {Array}
|
Returns an array of local Subscriber objects for a given stream. |
off
(type, handler, context)
→ {Object}
|
Removes an event handler or handlers. |
on
(type, handler, context)
→ {
EventDispatcher
}
|
Adds an event handler function for one or more events. |
once
(type, handler, context)
→ {Object}
|
Adds an event handler function for one or more events. |
publish
(publisher, completionHandler)
|
The
publish()
method starts publishing an audio-video stream to the session.
|
removeEventListener
(type, listener, context)
|
Deprecated. |
setEncryptionSecret
(secret)
→ {Promise}
|
Sets the encryption secret for a session with end-to-end encryption enabled. |
setIceConfig
(newIceConfig)
|
Sets the ICE configuration for all connections in a session. |
signal
(signal, completionHandler)
|
Sends a signal to each client or a specified client in the session. |
subscribe
(stream, targetElement, properties, completionHandler)
→ {
Subscriber
}
|
Subscribes to a stream that is available to the session. |
unpublish
(publisher
)
|
Ceases publishing the specified publisher's audio-video stream to the session. |
unsubscribe
(subscriber)
|
Stops subscribing to a stream in the session. |
addEventListener (type, listener, context)
Parameters:
Name | Type | Description |
---|---|---|
type |
String | The string identifying the type of event. |
listener |
function | The function to be invoked when the object dispatches the event. |
context |
Object |
(Optional) Defines the value of
this
in the event handler function.
|
- See:
Deprecated — use on() or once() instead.
This method registers a method as an event listener for a specific event.
If a handler is not registered for an event, the event is ignored locally. If the event listener function does not exist, the event is ignored locally.
Throws an exception if the
listener
name is invalid.
connect (token, completionHandler)
Upon a successful connection, the completion handler (the second parameter of the method) is invoked without an error object passed in. (If there is an error connecting, the completion handler is invoked with an error object.) Make sure that you have successfully connected to the session before calling other methods of the Session object.
The Session object dispatches a
connectionCreated
event when any client (including your own) connects to the
session.
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.nexmo.com
var sessionID = ""; // Replace with your own session ID.
// See https://developer.vonage.com/en/video/guides/create-session/.
var token = ""; // Replace with a generated token.
// See https://developer.vonage.com/en/video/guides/create-token/.
var session = OT.initSession(apiKey, sessionID);
session.connect(token, function(error) {
if (error) {
console.log(error.message);
} else {
// You have connected to the session. You could publish a stream now.
}
});
Events dispatched:
exception
(
ExceptionEvent
) — Dispatched by the OT 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. However, you can pass a completion handler
function in as the second parameter of the
connect()
and use this function instead of a listener for the
sessionConnected
event.
Parameters:
Name | Type | Description |
---|---|---|
token |
String | The session token. You generate a session token using our server-side libraries or at your Vonage Video API account page. For more information, see Connection token creation . |
completionHandler |
function |
(Optional) A function to be called when the call to the
connect()
method succeeds or fails. This function takes one parameter —
error
(see the
Error
object). On success, the
completionHandler
function is not passed any arguments. On error, the function
is passed an
error
object parameter (see the
Error
object). The
error
object has two properties:
code
(an integer) and
message
(a string), which identify the cause of the failure. The
following code adds a
completionHandler
when calling the
connect()
method:
Note that upon connecting to the session, the Session object
dispatches a
|
- See:
disableForceMute () → {Promise}
After you call to the
Session.forceMuteAll()
method (or a moderator in another client makes a call to mute all
streams), any streams published after the moderation call are
published with audio muted. Call the
disableForceMute()
method to remove the mute state of a session (so that new
published streams are not automatically muted).
Calling this method causes the Session object in each connected
clients to dispatch a
muteForced
event, with the
active
flag set to
false
.
Check the
capabilities.canForceMute
property of the Session object to see if you can call this
function successfully. This is reserved for clients that have
connected with a token that has been assigned the moderator role
(see the
Token Creation
documentation).
Returns:
name
property of the Error object is set to one of the following values,
depending the type of error:
-
'OT_NOT_CONNECTED'
— The client is not connect to the session. -
'OT_PERMISSION_DENIED'
— The user's role does not include permissions required to force other users to mute. You define a user's role when you create the user token (see the Token creation overview ). You pass the token string as a parameter of theconnect()
method of the Session object. -
'OT_UNEXPECTED_SERVER_RESPONSE'
— In case of an internal server error.
disconnect ()
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 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.
If the session is not currently connected, calling this method causes a warning to be logged. See OT.setLogLevel() .
Note:
If you intend to reuse a Publisher object to publish to different
sessions (or the same session) sequentially, add an event listener
for the
streamDestroyed
event dispatched by the Publisher object (when it stops
publishing). In the event listener, call the
preventDefault()
method of the event object to prevent the Publisher's video from
being removed from the page.
Events dispatched:
sessionDisconnected
(
SessionDisconnectEvent
) — Dispatched locally when the connection is disconnected.
connectionDestroyed
(
ConnectionEvent
) — Dispatched on other clients, along with the
streamDestroyed
event (as warranted).
streamDestroyed
(
StreamEvent
) — Dispatched on other clients if streams are lost as a result of
the session disconnecting.
forceDisconnect (connection, completionHandler)
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 OT 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 (see the
Token creation overview
). See
ExceptionEvent
and
OT.on()
.
The application throws an error if the session is not connected.
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.
Parameters:
Name | Type | Description |
---|---|---|
connection |
Connection |
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).
|
completionHandler |
function |
(Optional) A function to be called when the call to the
forceDiscononnect()
method succeeds or fails. This function takes one parameter —
error
. On success, the
completionHandler
function is not passed any arguments. On error, the function
is passed an
error
object parameter. The
error
object, defined by the
Error
class, has two properties:
code
(an integer) and
message
(a string), which identify the cause of the failure. Calling
forceDisconnect()
fails if the role assigned to your token is not "moderator";
in this case the
error.name
property is set to
"OT_PERMISSION_DENIED"
. The following code adds a
completionHandler
when calling the
forceDisconnect()
method:
|
forceMuteAll (excludedStreams) → {Promise}
A stream published by the moderator calling the
forceMuteAll()
method is muted along with other streams in the session, unless
you add the moderator's stream (or streams) to the excluded
streams array.
If you leave out the
excludedStreams
parameter, all streams in the session (including those of the
moderator) will stop publishing audio:
session.forceMuteAll();
Also, any streams that are published after the call to the
forceMuteAll()
method are published with audio muted. You can remove the mute
state of a session by calling the
disableForceMute()
method of the Session object.
session.disableForceMute();
After you call the
Session.disableForceMute()
method, new streams published to the session will no longer have
audio muted.
Calling this method causes the Publisher objects in the clients
publishing the streams to dispatch
muteForced
events. Also, the Session object in each client connected to the
session dispatches the
muteForced
event (with the
active
property of the event object set to
true
).
Check the
capabilities.canForceMute
property of the Session object to see if you can call this
function successfully. This is reserved for clients that have
connected with a token that has been assigned the moderator role
(see the
Token Creation
documentation).
Parameters:
Name | Type | Description |
---|---|---|
excludedStreams |
Array | An array of Stream objects to be excluded from being muted. Note that if you want to prevent the local client's published stream(s) from being muted, include the Stream object(s) for those stream(s) in this array. |
- See:
Returns:
name
property of the Error object is set to one of the following values,
depending the type of error:
-
'OT_NOT_CONNECTED'
— The client is not connect to the session. -
'INVALID_PARAMETER'
— if one or more of the passed parameters are invalid. -
'OT_PERMISSION_DENIED'
— The user's role does not include permissions required to force other users to mute. You define a user's role when you create the user token (see the Token creation overview ). You pass the token string as a parameter of theconnect()
method of the Session object. -
'OT_UNEXPECTED_SERVER_RESPONSE'
— in case of an internal server error.
forceMuteStream (stream) → {Promise}
Calling this method causes the Publisher object in the client
publishing the stream to dispatch a
muteForced
event.
Check the
capabilities.canForceMute
property of the Session object to see if you can call this
function successfully. This is reserved for clients that have
connected with a token that has been assigned the moderator role
(see the
Token Creation
documentation).
Parameters:
Name | Type | Description |
---|---|---|
stream |
Stream | The stream to be muted. |
- See:
Returns:
name
property of the Error object is set to one of the following values,
depending the type of error:
-
'OT_NOT_CONNECTED'
— The client is not connect to the session. -
'OT_INVALID_PARAMETER'
— if one or more of the passed parameters are invalid. -
'OT_PERMISSION_DENIED'
— The user's role does not include permissions required to force other users to mute. You define a user's role when you create the user token (see the Token creation overview ). You pass the token string as a parameter of theconnect()
method of the Session object. -
'OT_NOT_FOUND'
— The stream wasn't found in this session. -
'OT_UNEXPECTED_SERVER_RESPONSE'
— In case of an internal server error.
forceUnpublish (stream, completionHandler)
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 OT 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 (see the
Token creation overview
). You pass the token string as a parameter of the
connect()
method of the Session object. See
ExceptionEvent
and
OT.on()
.
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.
Parameters:
Name | Type | Description |
---|---|---|
stream |
Stream | The stream to be unpublished. |
completionHandler |
function |
(Optional) A function to be called when the call to the
forceUnpublish()
method succeeds or fails. This function takes one parameter —
error
. On success, the
completionHandler
function is not passed any arguments. On error, the function
is passed an
error
object parameter. The
error
object, defined by the
Error
class, has two properties:
code
(an integer) and
message
(a string), which identify the cause of the failure. Calling
forceUnpublish()
fails if the role assigned to your token is not "moderator";
in this case the
error.name
property is set to
"OT_PERMISSION_DENIED"
. The following code adds a completion handler when calling
the
forceUnpublish()
method:
|
getPublisherForStream (stream) → { Publisher }
Parameters:
Name | Type | Description |
---|---|---|
stream |
Stream | The stream for which you want to find the Publisher. |
Returns:
null
if there is no local Publisher object for the specified stream.
getSubscribersForStream (stream) → {Array}
Parameters:
Name | Type | Description |
---|---|---|
stream |
Stream | The stream for which you want to find subscribers. |
Returns:
off (type, handler, context) → {Object}
If you pass in one event name and a handler method, the handler is removed for that event:
obj.off("eventName", eventHandler);
If you pass in multiple event names and a handler method, the handler is removed for those events:
obj.off("eventName1 eventName2", eventHandler);
If you pass in an event name (or names) and no handler method, all handlers are removed for those events:
obj.off("event1Name event2Name");
If you pass in no arguments, all event handlers are removed for all events dispatched by the object:
obj.off();
The method also supports an alternate syntax, in which the first parameter is an object that is a hash map of event names and handler functions and the second parameter (optional) is the context for this in each handler:
obj.off(
{
eventName1: event1Handler,
eventName2: event2Handler
});
Parameters:
Name | Type | Description |
---|---|---|
type |
String |
(Optional) The string identifying the type of event. You can
use a space to specify multiple events, as in "accessAllowed
accessDenied accessDialogClosed". If you pass in no
type
value (or other arguments), all event handlers are removed for
the object.
|
handler |
function |
(Optional) The event handler function to remove. The handler
must be the same function object as was passed into
on()
. Be careful with helpers like
bind()
that return a new function when called. If you pass in no
handler
, all event handlers are removed for the specified event
type
.
|
context |
Object |
(Optional) If you specify a
context
, the event handler is removed for all specified events and
handlers that use the specified context. (The context must
match the context passed into
on()
.)
|
Returns:
on (type, handler, context) → { EventDispatcher }
The following code adds an event handler for one event:
obj.on("eventName", function (event) {
// This is the event handler.
});
If you pass in multiple event names and a handler method, the handler is registered for each of those events:
obj.on("eventName1 eventName2",
function (event) {
// This is the event handler.
});
You can also pass in a third
context
parameter (which is optional) to define the value of
this
in the handler method:
obj.on("eventName",
function (event) {
// This is the event handler.
},
obj);
The method also supports an alternate syntax, in which the first parameter is an object that is a hash map of event names and handler functions and the second parameter (optional) is the context for this in each handler:
obj.on(
{
eventName1: function (event) {
// This is the handler for eventName1.
},
eventName2: function (event) {
// This is the handler for eventName2.
}
},
obj);
If you do not add a handler for an event, the event is ignored locally.
Parameters:
Name | Type | Description |
---|---|---|
type |
String | The string identifying the type of event. You can specify multiple event names in this string, separating them with a space. The event handler will process each of the events. |
handler |
function | The handler function to process the event. This function takes the event object as a parameter. |
context |
Object |
(Optional) Defines the value of
this
in the event handler function.
|
Returns:
once (type, handler, context) → {Object}
on()
method to add an event handler, the handler is
not
removed when it is called.) The
once()
method is the equivilent of calling the
on()
method and calling
off()
the first time the handler is invoked.
The following code adds a one-time event handler for one event:
obj.once("eventName", function (event) {
// This is the event handler.
});
If you pass in multiple event names and a handler method, the handler is registered for each of those events:
obj.once("eventName1 eventName2"
function (event) {
// This is the event handler.
});
You can also pass in a third
context
parameter (which is optional) to define the value of
this
in the handler method:
obj.once("eventName",
function (event) {
// This is the event handler.
},
obj);
The method also supports an alternate syntax, in which the first parameter is an object that is a hash map of event names and handler functions and the second parameter (optional) is the context for this in each handler:
obj.once(
{
eventName1: function (event) {
// This is the event handler for eventName1.
},
eventName2: function (event) {
// This is the event handler for eventName1.
}
},
obj);
Parameters:
Name | Type | Description |
---|---|---|
type |
String | The string identifying the type of event. You can specify multiple event names in this string, separating them with a space. The event handler will process the first occurence of the events. After the first event, the handler is removed (for all specified events). |
handler |
function | The handler function to process the event. This function takes the event object as a parameter. |
context |
Object |
(Optional) Defines the value of
this
in the event handler function.
|
Returns:
publish (publisher, completionHandler)
publish()
method starts publishing an audio-video stream to the session. The
audio-video stream is captured from a local microphone and webcam.
Upon successful publishing, the Session objects on all connected
clients dispatch the
streamCreated
event.
You pass a Publisher object as the one parameter of the method.
You can initialize a Publisher object by calling the
OT.initPublisher()
method. Before calling
Session.publish()
.
This method takes an alternate form:
publish(targetElement: String | HTMLElement, properties: Object,
completionHandler: Function): Publisher
— In this form, you do
not
pass a Publisher object into the function. Instead, you pass in a
targetElement
(the target HTML element or the ID of the target HTML element for
the Publisher), an optional
properties
object that defines options for the Publisher (see
OT.initPublisher()
), and an optional completion handler function. The method returns
a new Publisher object, which starts sending an audio-video stream
to the session. The remainder of this documentation describes the
form that takes a single Publisher object as a parameter.
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 web page alerts the user to grant access to the camera and microphone.
The OT 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 (see
Token creation overview
). You pass the token string as a parameter of the
connect()
method of the Session object. See
ExceptionEvent
and
OT.on()
.
The application throws an error if the session is not connected.
Events dispatched:
exception
(
ExceptionEvent
) — Dispatched by the OT object. This can occur when user's role
does not allow publishing (the
code
property of event object is set to 1500); it can also occur if the
connection fails to connect (the
code
property of event object is set to 1013). WebRTC is a peer-to-peer
protocol, and it is possible that connections will fail to
connect. The most common cause for failure is a firewall that the
protocol cannot traverse.
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.nexmo.com
var sessionId = ""; // Replace with your own session ID.
// https://developer.vonage.com/en/video/guides/create-session/.
var token = ""; // Replace with a generated token that has been assigned the publish role.
// See https://developer.vonage.com/en/video/guides/create-token/.
var session = OT.initSession(apiKey, sessionID);
session.connect(token, function(error) {
if (error) {
console.log(error.message);
} else {
var publisherOptions = {width: 400, height:300, name:"Bob's stream"};
// This assumes that there is a DOM element with the ID 'publisher':
publisher = OT.initPublisher('publisher', publisherOptions);
session.publish(publisher);
}
});
Parameters:
Name | Type | Description |
---|---|---|
publisher |
Publisher | A Publisher object, which you initialize by calling the OT.initPublisher() method. |
completionHandler |
function |
(Optional) A function to be called when the call to the
publish()
method succeeds or fails. This function takes one parameter —
error
. On success, the
completionHandler
function is not passed any arguments. On error, the function
is passed an
error
object parameter (see the
Error
object). The
error
object has two properties:
code
(an integer) and
message
(a string), which identify the cause of the failure. Calling
publish()
fails if the role assigned to your token is not "publisher" or
"moderator"; in this case the
error.name
property is set to
"OT_PERMISSION_DENIED"
. Calling
publish()
also fails if the client fails to connect; in this case the
error.name
property is set to
"OT_NOT_CONNECTED"
. The following code adds a completion handler when calling
the
publish()
method:
|
Returns:
removeEventListener (type, listener, context)
Parameters:
Name | Type | Description |
---|---|---|
type |
String | The string identifying the type of event. |
listener |
function | The event listener function to remove. |
context |
Object |
(Optional) If you specify a
context
, the event handler is removed for all specified events and
event listeners that use the specified context. (The context
must match the context passed into
addEventListener()
.)
|
- See:
Deprecated — use off() instead.
Removes an event listener for a specific event.
Throws an exception if the
listener
name is invalid.
setEncryptionSecret (secret) → {Promise}
Parameters:
Name | Type | Description |
---|---|---|
secret |
string | The encryption secret. |
Returns:
name
property of the Error object is set to one of the following values,
depending the type of error:
-
'OT_INVALID_ENCRYPTION_SECRET'
; The secret is invalid.
-
A secret mismatch may occur when no error is dispatched. See
subscrriber events
for more information.
setIceConfig (newIceConfig)
This feature is available for projects that use the configurable TURN server add-on .
Parameters:
Name | Type | Description |
---|---|---|
newIceConfig |
IceConfig |
This object defines the ICE configuration. It has the
following propoerties;
|
- See:
signal (signal, completionHandler)
to
property of the
signal
parameter to limit the signal to be sent to a specific client;
otherwise the signal is sent to each client connected to the
session.
The following example sends a signal of type "foo" with a specified data payload ("hello") to all clients connected to the session:
session.signal({
type: "foo",
data: "hello"
},
function(error) {
if (error) {
console.log("signal error: " + error.message);
} else {
console.log("signal sent");
}
}
);
Calling this method without specifying a recipient client (by
setting the
to
property of the
signal
parameter) results in multiple signals sent (one to each client in
the session). For information on charges for signaling, see the
OpenTok pricing
page.
The following example sends a signal of type "foo" with a data payload ("hello") to a specific client connected to the session:
session.signal({
type: "foo",
to: recipientConnection; // a Connection object
data: "hello"
},
function(error) {
if (error) {
console.log("signal error: " + error.message);
} else {
console.log("signal sent");
}
}
);
Add an event handler for the
signal
event to listen for all signals sent in the session. Add an event
handler for the
signal:type
event to listen for signals of a specified type only (replace
type
, in
signal:type
, with the type of signal to listen for). The Session object
dispatches these events. (See
events
.)
Parameters:
Name | Type | Description | ||||||||
---|---|---|---|---|---|---|---|---|---|---|
signal |
Object |
An object that contains the following properties defining the
signal:
Each property is optional. If you set none of the properties, you will send a signal with no data or type to each client connected to the session. |
||||||||
completionHandler |
function |
(Optional) A function that is called when sending the signal
succeeds or fails. This function takes one parameter —
error
. On success, the
completionHandler
function is not passed any arguments. On error, the function
is passed an
error
object, defined by the
Error
class. The
error
object has the following properties:
Note that the
|
- See:
-
- signal and signal:type events
subscribe (stream, targetElement, properties, completionHandler) → { Subscriber }
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
targetElement
does not exist in the HTML DOM
.
Example
The following code subscribes to other clients' streams:var apiKey = ""; // Replace with your API key. See https://dashboard.nexmo.com
var sessionID = ""; // Replace with your own session ID.
// See https://developer.vonage.com/en/video/guides/create-session/.
var token = ""; // Replace with a generated token.
// See https://developer.vonage.com/en/video/guides/create-token/.
var session = OT.initSession(apiKey, sessionID);
session.on("streamCreated", function(event) {
subscriber = session.subscribe(event.stream, targetElement);
});
session.connect(token);
Parameters:
Name | Type | Description |
---|---|---|
stream |
Stream | The Stream object representing the stream to which we are trying to subscribe. |
targetElement |
Object |
(Optional) The DOM element or the
id
attribute of the existing DOM element used to determine the
location of the Subscriber video in the HTML DOM. See the
insertMode
property of the
properties
parameter. If you do not specify a
targetElement
, the application appends a new DOM element to the HTML
body
.
|
properties |
Object |
This is an object that contains the following properties:
|
completionHandler |
function |
(Optional) A function to be called when the call to the
subscribe()
method succeeds or fails. This function takes one parameter —
error
. On success, the
completionHandler
function is not passed any arguments. On error, the function
is passed an
error
object, defined by the
Error
class, has two properties:
code
(an integer) and
message
(a string), which identify the cause of the failure. The
following code adds a
completionHandler
when calling the
subscribe()
method:
|
Returns:
unpublish (publisher )
streamDestroyed
event.
To prevent the Publisher from being removed from the DOM, add an
event listener for the
streamDestroyed
event dispatched by the Publisher object and call the
preventDefault()
method of the event object.
Note:
If you intend to reuse a Publisher object to publish to different
sessions (or the same session) sequentially, add an event listener
for the
streamDestroyed
event dispatched by the Publisher object (when it stops
publishing). In the event listener, call the
preventDefault()
method of the event object to prevent the Publisher's video from
being removed from the page.
Events dispatched:
streamDestroyed
(
StreamEvent
) — The stream associated with the Publisher has been destroyed.
Dispatched on by the Publisher on on the Publisher's browser.
Dispatched by the Session object on all other 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 apiKey = ""; // Replace with your API key. See https://dashboard.nexmo.com
var sessionID = ""; // Replace with your own session ID.
// See https://developer.vonage.com/en/video/guides/create-session/.
var token = ""; // Replace with a generated token.
// See https://developer.vonage.com/en/video/guides/create-token/.
var publisher;
var session = OT.initSession(apiKey, sessionID);
session.connect(token, function(error) {
if (error) {
console.log(error.message);
} else {
// This assumes that there is a DOM element with the ID 'publisher':
publisher = OT.initPublisher('publisher');
session.publish(publisher);
}
});
function unpublish() {
session.unpublish(publisher);
}
</script>
<body>
<div id="publisherContainer/>
<br/>
<a href="javascript:unpublish()">Stop Publishing</a>
</body>
Parameters:
Name | Type | Description |
---|---|---|
publisher |
Publisher | The Publisher object to stop streaming. |
unsubscribe (subscriber)
Example
The following code subscribes to other clients' streams. For each stream, the code also adds an Unsubscribe link.
var apiKey = ""; // Replace with your API key. See See https://dashboard.nexmo.com
var sessionID = ""; // Replace with your own session ID.
// See https://developer.vonage.com/en/video/guides/create-session/.
var token = ""; // Replace with a generated token.
// See https://developer.vonage.com/en/video/guides/create-token/.
var streams = [];
var session = OT.initSession(apiKey, sessionID);
session.on("streamCreated", function(event) {
var stream = event.stream;
displayStream(stream);
});
session.connect(token);
function displayStream(stream) {
var div = document.createElement('div');
div.setAttribute('id', 'stream' + stream.streamId);
var subscriber = session.subscribe(stream, div);
subscribers.push(subscriber);
var aLink = document.createElement('a');
aLink.setAttribute('href', 'javascript: unsubscribe("' + subscriber.id + '")');
aLink.innerHTML = "Unsubscribe";
var streamsContainer = document.getElementById('streamsContainer');
streamsContainer.appendChild(div);
streamsContainer.appendChild(aLink);
streams = event.streams;
}
function unsubscribe(subscriberId) {
console.log("unsubscribe called");
for (var i = 0; i < subscribers.length; i++) {
var subscriber = subscribers[i];
if (subscriber.id == subscriberId) {
session.unsubscribe(subscriber);
}
}
}
Parameters:
Name | Type | Description |
---|---|---|
subscriber |
Subscriber | The Subscriber object to unsubcribe. |
- See:
Events
archiveStarted
archiveStopped
connectionCreated
sessionConnected
event when your local client connects.)
connectionDestroyed
- See:
cpuPerformanceChanged
muteForced
active
property of this MuteForcedEvent object is set to
true
), or a moderator has disabled the mute audio state in the session
(the
active
property of this MuteForcedEvent object is set to
false
).
- See:
sessionConnected
connect()
method of a Session object. Before calling the
connect()
method, initialize the session by calling the
OT.initSession()
method. For a code example and more details, see
Session.connect()
.
sessionDisconnected
disconnect()
method of the Session object. The event may also be dispatched if a
session connection is lost inadvertently, as in the case of a lost
network connection.
The default behavior is that all Subscriber objects are
unsubscribed and removed from the HTML DOM. Each Subscriber object
dispatches a
destroyed
event when the element is removed from the HTML DOM. If you call
the
preventDefault()
method in the event listener for the
sessionDisconnect
event, the default behavior is prevented, and you can, optionally,
clean up Subscriber objects using your own code.
The
reason
property of the event object indicates the reason for the client
being disconnected.
sessionReconnected
sessionReconnecting
event, prior to the
sessionReconnected
event. If the client cannot reconnect to the session, the Session
object dispatches a
sessionDisconnected
event instead of this event.
Any existing publishers and subscribers are automatically reconnected when client reconnects and the Session object dispatches this event.
Any signals sent by other clients while your client was
disconnected are received upon reconnecting. By default, signals
initiated by the local client while disconnected (by calling the
Session.signal()
method) are sent when the client reconnects to the OpenTok
session. You can prevent this by setting the
retryAfterReconnect
property to
false
in the
signal
object you pass into the
Session.signal()
method.
sessionReconnecting
sessionReconnected
event. Otherwise, if the client cannot reconnect, the Session object
dispatches a
sessionDisconnected
event.
In response to this event, you may want to provide a user interface notification, to let the user know that the app is trying to reconnect to the session and that audio-video streams are temporarily disconnected.
signal
-
data
— (String) The data string sent with the signal (if there is one). -
from
— ( Connection ) The Connection corresponding to the client that sent the signal. -
type
— (String) The type assigned to the signal (if there is one).
You can register to receive all signals sent in the session, by
adding an event handler for the
signal
event. For example, the following code adds an event handler to
process all signals sent in the session:
session.on("signal", function(event) {
console.log("Signal sent from connection: " + event.from.id);
console.log("Signal data: " + event.data);
});
You can register for signals of a specified type by adding an
event handler for the
signal:type
event (replacing
type
with the actual type string to filter on).
- See:
streamCreated
streamCreated
event. For a code example and more details, see
StreamEvent
.
streamDestroyed
The default behavior is that all Subscriber objects that are
subscribed to the stream are unsubscribed and removed from the
HTML DOM. Each Subscriber object dispatches a
destroyed
event when the element is removed from the HTML DOM. If you call
the
preventDefault()
method in the event listener for the
streamDestroyed
event, the default behavior is prevented and you can clean up a
Subscriber object for the stream by calling its
destroy()
method. See
Session.getSubscribersForStream()
.
For streams published by your own client, the Publisher object
dispatches a
streamDestroyed
event.
For a code example and more details, see StreamEvent .
- See:
streamPropertyChanged
-
A stream has started or stopped publishing audio or video (see
Publisher.publishAudio()
and
Publisher.publishVideo()
). Note that a subscriber's video can be disabled or enabled for
reasons other than the publisher disabling or enabling it. A
Subscriber object dispatches
videoDisabled
andvideoEnabled
events in all conditions that cause the subscriber's stream to be disabled or enabled. -
The
videoDimensions
property of the Stream object has changed (see Stream.videoDimensions ). -
The
videoType
property of the Stream object has changed. This can happen in a stream published by a mobile device. (See Stream.videoType .)
- See:
signal:type
-
data
— (String) The data string sent with the signal. -
from
— ( Connection ) The Connection corresponding to the client that sent the signal. -
type
— (String) The type assigned to the signal (if there is one).
You can register for signals of a specfied type by adding an event
handler for the
signal:type
event (replacing
type
with the actual type string to filter on). For example, the
following code adds an event handler for signals of type "foo":
session.on("signal:foo", function(event) {
console.log("foo signal sent from connection " + event.from.id);
console.log("Signal data: " + event.data);
});
You can register to receive
all
signals sent in the session, by adding an event handler for the
signal
event.
- See: