The latest version of the OpenTok.js library uses WebRTC instead of Adobe Flash for audio-video communications. This guide assists you in migrating your website from version 1.0 to the latest version of the OpenTok.js library.
The latest OpenTok.js library interacts with the apps using the following OpenTok libraries:
If you are migrating code from version 2.0, see this page.
Set the src
attribute of the script
tag to the following URL to load
the latest version of the OpenTok.js library:
<script src="https://static.opentok.com/v2/js/opentok.min.js"></script>
You must create new sessions for use in the new OpenTok.js library. Sessions that were previously used in OpenTok 1.0 cannot be used in the latest version of OpenTok.
In version 1.0, streams were either sent directly between clients (peer-to-peer) or using
the OpenTok Media Router. When you created a session for version 1.0, using one of the OpenTok
server SDKs, you set a p2p.preference
parameter to "enabled"
or
"disabled"
. This changes in the latest version of OpenTok.
Now when you create a session, you specify how clients in the session will send audio-video streams, known as the media mode. There are two options:
Note: In the new versions of the OpenTok server SDKs, the default media mode is relayed. (In earlier versions, the default was to use the OpenTok Media Router.)
<script src="https://static.opentok.com/v2/js/opentok.min.js"></script>
Important: The latest OpenTok.js library includes changes that are not compatible with OpenTok.js 1.0. This section shows you how to adapt existing code to work with the latest OpenTok.js library.
The following classes, properties, methods, and events from version 1.0 are not included in the latest version of OpenTok.js.
Camera |
Replaced by the videoSource property of the properties parameter of
the OT.initPublisher() method.
|
Capabilities.publishH264 |
Not in OpenTok.js version 2. WebRTC does not support h.264 video. |
Connection.quality |
Not in OpenTok.js version 2. |
DeviceEvent |
Not in OpenTok.js version 2. |
DeviceManager |
See the videoSource parameter of the properties parameter of
the OT.initPublisher() method. |
DevicePanel |
See the videoSource and audioSource properties of the
properties parameter of the OT.initPublisher() method. |
DeviceStatusEvent |
Not in OpenTok.js version 2. |
IssueReportedEvent |
Not in OpenTok.js version 2. |
Microphone |
Replaced by the audioSource property of the properties
parameter of OT.initPublisher() . |
Publisher.replaceElementId |
Replaced by the Publisher.element property. |
Publisher.detectDevices() |
Replaced by OT.getDevices() . |
Publisher.detectMicActivity() |
Audio level API coming soon to version 2. |
Publisher.disableMicrophone() |
Replaced by Publisher.publishAudio(false) . |
Publisher.enableMicrophone() |
Replaced by Publisher.publishAudio(true) . |
Publisher.getEchoCancelationMode() |
Does not apply in OpenTok.js version 2, which has echo cancellation built in. |
Publisher.getMicrophoneGain() |
Not in OpenTok.js version 2. |
Publisher.setCamera() |
Replaced the videoSource property of the properties
parameter of |
Publisher.setMicrophone() |
Replaced the audioSource property of the properties
parameter of |
Publisher.setMicrophoneGain() |
Not in OpenTok.js version 2. |
Publisher deviceInactive event |
Not in OpenTok.js version 2. |
Publisher devicesDetected event |
Replaced by OT.getDevices() . |
Publisher echoCancellationModeChanged event |
Does not apply in OpenTok.js version 2, which has echo cancellation built in. |
Publisher invalidDeviceName event |
Replaced by an error if you call OT.initPublisher() and specify
an invalid videoSource property of the properties
parameter. |
Publisher microphoneActivityLevel event |
A replacement API will be available soon. |
Publisher microphoneGainChanged event |
Does not apply in OpenTok.js version 2. |
Publisher resize event |
Does not apply in OpenTok.js version 2. |
Publisher settingsButtonClick event |
Does not apply in OpenTok.js version 2. |
ResizeEvent |
Does not apply in OpenTok.js version 2. |
Session.cleanUp() |
Not in OpenTok.js version 2. |
Session.subscribe() properties.audioEnabled |
Replaced with Session.subscribe() properties.subscribeToAudio . |
Session.subscribe() properties.wMode |
Does not apply in OpenTok.js version 2. |
Session microphoneLevelChanged event |
Not in OpenTok.js version 2. |
Session signalReceived event |
Replace with the Session signal event. |
SignalEvent.fromConnection |
Renamed SignalEvent.from . |
Stream.quality |
Not in OpenTok.js version 2. |
StateManager |
Not in OpenTok.js version 2. |
Stream.type |
Does not apply in OpenTok version 2. |
Subscriber.disableAudio() |
Replaced with Subscriber.subscribeToAudio(false) . |
Subscriber.enableAudio() |
Replaced with Subscriber.subscribeToAudio(true) . |
TB.initDeviceManager() |
Replaced with OT.getDevices() . |
TB.initPublisher() properties.cameraName |
Replaced with TB.initPublisher() properties.videoSource . |
TB.initPublisher() properties.encodedHeight |
Replaced with TB.initPublisher() properties.resolution . |
TB.initPublisher() properties.encodedWidth |
Replaced with TB.initPublisher() properties.resolution . |
TB.initPublisher() properties.microphoneEnabled |
Replaced with TB.initPublisher() properties.publishAudio . |
TB.initPublisher() properties.microphoneGain |
Not in OpenTok version 2. |
TB.initPublisher() properties.microphoneName |
Replaced with TB.initPublisher() properties.audioSource . |
TB.initPublisher() properties.rememberDeviceAccess |
Does not apply in OpenTok version 2. |
TB.initPublisher() properties.reportMicLevels |
New API coming soon to OpenTok version 2. |
TB.initPublisher() properties.style.showMicButton |
Not in OpenTok version 2. |
TB.initPublisher() properties.style.showSettingsButton |
Does not apply in OpenTok version 2. |
TB.initPublisher() properties.wmode |
Does not apply in OpenTok version 2. |
TB.reportIssue() |
Not in OpenTok version 2. |
TB issueReported event |
Not in OpenTok version 2. |
ConnectionEvent.connections |
Replaced by the ConnectionEvent.connection property. See
Changes to stream and connection events. |
TB |
This has been renamed OT (for OpenTok). See The OT object. |
SessionConnectEvent |
Use the completion handler for the Session.connect() method. See
Completion handlers for methods. |
StreamEvent.streams |
Replaced by the StreamEvent.stream property. See
Changes to stream and connection events. |
The TB object has been renamed OT (for OpenTok). Note also that the URL for the OpenTok.js library now points to the opentok.min.js file:
<script src="https://static.opentok.com/v2/js/opentok.min.js"></script>
However, for backward compatibility, the JavaScript TB object will still work, and the TB.min.js URL will still work.
In the latest version of the OpenTok.js library, you pass your API key into the
OT.initSession()
method (as the first parameter):
var session = OT.initSession(apiKey, sessionId);
session.connect(token, function(error) {
if (!error) {
var publisher OT.initPublisher();
session.publish(publisher);
}
});
Note that the Session.connect()
method and the OT.initPublisher()
method do not take an API key as a parameter, since you pass the API key into the
OT.initSession()
method. (However, the old syntax is still supported.)
We have tried to maintain backward compatibility with version 1.0 of the OpenTok JavaScript library. However, some of the API changes require some code changes for apps ported from version 1.0.
The Session object does not dispatch streamCreated
events for streams your own client publishes.
To detect when a stream is created for your Publisher, add a completion handler for the Session.publish()
method:
var publisher = session.publish(publisher, properties, function(error) {
if (error) {
console.log("Failed to publish.")
} else {
console.log("Stream publishing.")
}
})
The Publisher object also dispatches a streamCreated
event for the stream it publishes.
Additionally, the Publisher object (not the Session object) now dispatches streamDestroyed
events
for the stream it publishes. If you want to retain the Publisher in the HTML DOM (for reuse), call the
preventDefault()
method in the event listener for the streamDestroyed
event dispatched
by the Publisher:
publisher = OT.initPublisher(apiKey)
.on("streamDestroyed", function(event) {
event.preventDefault(); // This lets you reuse the Publisher.
}
);
Calling the preventDefault()
method of the streamDestroyed
and
sessionDisconnected
event objects dispatched by the Session object no longer prevents the
Publisher object from being removed (as it did in version 1.0).
In the current OpenTok.js library, the connections
and streams
property of the
sessionConnected
event are deprecated, and they are set to empty arrays. The Session object
dispatches connectionCreated
and streamCreated
events for each client and stream in the
session, both when you connect and after you connect.
To detect if another client was in the session when you connect, compare the connection.creationTime
property
of the connectionCreated
event object with the connection.creationTime
property of the
Session object:
session.on("connectionCreated", function(event) {
if (event.connection.creationTime <= session.connection.creationTime) {
console.log("Detected a client that connected before you.")
}
}
For more details, see Changes to stream and connection events.
In version 1.0, the Session.signal()
method simply pings all clients connected to the session.
The latest version of the OpenTok.js library introduces a new signaling API, with more capabilities. You can
now include a data string in the signal, and you can signal the entire session or specific clients connected
to the session. For details, see the JavaScript Signaling
tutorial.
To learn about other changes and to start taking advantage of other new features, see New features.
completionHandler
parameter. This parameter is
a function that is called when the method succeeds or fails.on()
, once()
, and off()
— for adding and removing
event listeners.accessAllowed
property lets you see whether a client has allowed access to the camera and
microphone.
ArchiveEvent |
See Archiving. |
ConnectionEvent.connection |
See Changes to stream and connection events. |
OT |
See The OT object. |
OT.initPublisher() properties.audioSource |
See Setting the camera and microphone used by the publisher. |
OT.initPublisher() properties.frameRate |
See Intelligent quality control. |
OT.initPublisher() properties.insertMode |
See Publisher and Subscriber DOM APIs. |
OT.initPublisher() properties.resolution |
See Intelligent quality control. |
OT.initPublisher() properties.videoSource |
See Setting the camera and microphone used by the publisher. |
Publisher.accessAllowed |
See New Publisher.accessAllowed property. |
Publisher.element |
See Publisher and Subscriber DOM APIs. |
Publisher.id |
See Publisher and Subscriber DOM APIs. |
Publisher.stream |
See the Publisher class reference. |
Publisher destroyed event |
See Publisher and Subscriber DOM APIs. |
Publisher streamCreated event |
See Changes to stream and connection events. |
Publisher streamDestroyed event |
See Changes to stream and connection events. |
Session.subscribe() properties.insertMode |
See Publisher and Subscriber DOM APIs. |
Session archiveStarted event |
See Archiving. |
Session archiveStopped event |
See Archiving. |
Session signal event |
See Signaling. |
Session signal:type event |
See Signaling. |
SignalEvent.from |
See Signaling. |
SignalEvent.data |
See Signaling. |
Stream.frameRate |
See Intelligent quality control. |
Stream.videoDimensions |
See Intelligent quality control. |
StreamEvent.stream |
See Changes to stream and connection events. |
Subscriber.element |
See Publisher and Subscriber DOM APIs. |
The latest version of the OpenTok.js library adds features for setting recommended video resolution and frame rate for a published stream.
To set a recommended video resolution for a published stream, set the resolution
property of the
properties
parameter you pass into the OT.initPublisher()
method:
var publisherProperties = {resolution: "1280x720"};
var publisher = OT.initPublisher(apiKey, targetElement, publisherProperties);
This resolution
property is a string, defining the desired resolution of the video. The format of the string
is "widthxheight"
, where the width and height are represented in pixels. Valid values are
"1280x720"
, "640x480"
, and "320x240"
.
The requested resolution of a video stream is set as the videoDimensions.width
and
videoDimensions.height
properties of the Stream object.
The default resolution for a stream (if you do not specify a resolution) is 640x480 pixels. If the client system cannot support the resolution you requested, the the stream will use the next largest setting supported.
To set a recommended frame rate for a published stream, set the frameRate
property of the
properties
parameter you pass into the OT.initPublisher()
method:
var publisherProperties = {frameRate: 7};
var publisher = OT.initPublisher(apiKey, targetElement, publisherProperties);
Set the value to the the desired frame rate, in frames per second, of the video. Valid values are 30, 15, 7, and 1.
If the publisher specifies a frame rate, the actual frame rate of the video stream is set as the frameRate
property of the Stream object, though the actual frame rate will vary based on changing network and system conditions.
If the developer does not specify a frame rate, this property is undefined.
For sessions that use the OpenTok Media Router (sessions with the media mode set to routed), lowering the frame rate or lowering the resolution reduces the maximum bandwidth the stream can use. However, in sessions that have the media mode set to relayed, lowering the frame rate or resolution may not reduce the stream's bandwidth.
You can also restrict the frame rate of a Subscriber's video stream. To restrict the frame rate a Subscriber,
call the restrictFrameRate()
method of the subscriber, passing in true
:
mySubscriber.restrictFrameRate(true);
Pass in false
and the frame rate of the video stream is not restricted:
mySubscriber.restrictFrameRate(false);
When the frame rate is restricted, the Subscriber video frame will update once or less per second.
This feature is only available in sessions media mode set to routed, not in sessions with the media mode set to relayed. In relayed sessions, calling this method has no effect.
Restricting the subscriber frame rate has the following benefits:
Reducing a subscriber's frame rate has no effect on the frame rate of the video in other clients.
Finally, in sessions that use the OpenTok Media Router, a subscriber can drop to audio-only when
the OpenTok Media Router determines that the client's network conditions do not support video. This
feature was not available in OpenTok.js 1.0. In the latest OpenTok library, if the client's network
connectivity improves enough to support video, the client dispatches a videoEnabled
event, and the video resumes.
Some methods in the OpenTok.js library now include a new completionHandler
parameter. For this optional parameter,
you can pass in a function that is called when the method succeeds or fails.
For example the connect()
method of a Session object now includes a completionHandler parameter.
This is the last parameter of the method. 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 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:
// Set apiKey and token to your API key and a token for the session.
session.connect(apiKey, token, function(error) {
if (error) {
console.log(error.message);
} else {
console.log("Connected to session.");
}
});
Note that upon connecting to the session, the Session object dispatches a sessionConnected
event
in addition to calling the completionHandler
. However, the completionHandler
in the OpenTok.js library
provides a standard way for checking the success or failure of a method call.
The following methods each include a completionHander
parameter, as the last parameter of the method:
OT.initPublisher()
Session.connect()
Session.forceDisconnect()
Session.forceUnpublish()
Session.publish()
Session.signal()
Session.subscribe()
Check the message
property for more details about the error.
In the event of an error, the code
value of the error
parameter is set
to an Error object. For more information, see the documentation of the OpenTok
Error class.
The OpenTok.js library now includes new methods — on()
, once()
,
and off()
— for adding and removing event listeners. These methods are added
to each class that can dispatch an event:
The addEventListener()
and removeEventListener()
methods are
deprecated. They are replaced by the new methods. The new methods have the following
advantages:
on()
or off()
.
For example, the following code adds event listeners for the
accessAllowed
, accessDenied
, and
streamDestroyed
events for a Publisher object:
publisher.on({
accessAllowed: function (event) {
// This is the handler for the accessAllowed event.
},
accessDenied: function (event) {
// This is the handler for accessDenied.
}
streamDestroyed: function (event) {
// This is the handler for the streamDestroyed event.
},
});
once()
method lets you easily add an event listener that is called
only once. (It is equivalent to calling on()
and then calling
off()
in the event handler function.
context
parameter to set the value of this
in the handler method.
The OpenTok.js library now adds a number of improvements to events related to streams and clients being added to and leaving a session.
In the latest OpenTok.js library, the ConnectionEvent
class, which defines the connectionCreated
and
connectionDestroyed
events, has a connection
property, representing the single Connection created
or destroyed. The connections
property (from version 1.0) is deprecated.
Similarly, the StreamEvent
class, which defines the streamCreated
and streamDestroyed
events, has a stream
property, representing the single Stream created or destroyed. The streams
property (from version 1.0) is deprecated.
So, to detect other clients and their streams in a session (when you first connect or afterwards), simply register event
listeners for the connectionCreated
and streamCreated
events dispatched by the session object:
var connectionCount = 0;
session.on(
{
connectionCreated: function(event) {
connectionCount++;
console.log("New client: " event.connection.connectionId);
console.log("Clients in the session: " connectionCount);
},
connectionDestroyed: function(event) {
connectionCount--;
console.log("Client left the session: " event.connection.connectionId);
console.log("Clients in the session: " connectionCount);
},
streamCreated: function(event) {
console.log("Stream created: " event.stream.streamId);
// This is another client's stream, so you may want to subscribe to it.
},
streamDestroyed: function(event) {
console.log("Stream destroyed: " event.stream.streamId);
// This is another client's stream leaving the session.
}
}
).connect(apiKey, token, function(error) {
if (error) {
console.log("Failed to connect: " error.message);
} else {
connectionCount++;
}
});
In version 2 of the OpenTok.js library, the connections
and streams
property of the
sessionConnected
event are deprecated, and they are set to empty arrays. In version 2, the Session object
dispatches connectionCreated
and streamCreated
events for each client and stream in the
session, both when you connect and after you connect.
To detect other clients that exist in a session when you connect, compare the connection.creationTime
property of the connectionCreated
event and compare it with the connection.creationTime
property of the Session object:
session.on("connectionCreated", function(event) {
if (event.connection.creationTime <= session.connection.creationTime) {
console.log("Detected a client that connected before you.")
}
}
You can use the completion handler for the Session.connect()
method instead of the sessionConnected
event (as shown in the sample code).
In version 2 of the OpenTok.js library, a Publisher object (not the Session object) dispatches
streamCreated
and streamDestroyed
events for streams it publishes.
publisher = OT.initPublisher(apiKey)
.on(
{
streamCreated: function(event) {
// The Publisher started streaming.
},
streamDestroyed: function(event) {
// The Publisher stopped streaming.
}
}
);
The Session object does not dispatch streamCreated
events for streams your own client publishes.
So, there is no need to check to see if this event corresponds to one of your own published streams. For example, if you
want to subscribe to all third-party streams in the session, you can simply use the following code:
session.on("streamCreated", function(event) {
session.subscribe(event.stream);
},
}
If you want to retain the Publisher in the HTML DOM (for reuse), call the preventDefault()
method in the event
listener for the streamDestroyed
event dispatched by the Publisher:
publisher = OT.initPublisher(apiKey)
.on("streamDestroyed", function(event){
event.preventDefault(); // This lets you reuse the Publisher.
}
);
Calling the preventDefault()
method of the sessionDisconnected
event no longer causes
a Publisher to be preserved.
version 2 of the OpenTok.js library includes new APIs for Publisher and Subscriber insertion into and removal from the HTML DOM.
The insertMode
property of the properties
parameter of the OT.initPublisher()
specifies how the Publisher object will be inserted in the HTML DOM, in relation to the targetElement
parameter. You can set this parameter to one of the following values:
"replace"
The Publisher object replaces contents of the targetElement. This is
the default."after"
The Publisher object is a new element inserted after the targetElement in
the HTML DOM. (Both the Publisher and targetElement have the same parent element.)"before"
The Publisher object is a new element inserted before the targetElement in
the HTML DOM. (Both the Publisher and targetElement have the same parent element.)"append"
The Publisher object is a new element added as a child of the targetElement.
If there are other child elements, the Publisher is appended as the last child element of the targetElement.
For example, the following code adds a new Publisher object as a child of a publisherContainer
DOM element:
var publisherProperties = {insertMode: "append"};
var publisher = OT.initPublisher('publisher', publisherContainer, function(error) {
if (error) {
console.log(error);
} else {
console.log("Publisher initialized.");
}
});
Each Publisher and Subscriber object has an element
property, which is set to the HTML DOM element
containing the publisher or subscriber.
Each Publisher and Subscriber object dispatches a destroyed
event when the object has been removed from
the HTML DOM. In response to this event, you may choose to adjust (or remove) DOM elements related to the publisher
or subscriber that was removed.
The new accessAllowed
property indicates whether a client has granted access to the camera and microphone.
In addition, the Publisher still dispatches accessAllowed
and accessDenied
events, as it did
in version 1.0.