Suggestions

close search

Subscriber

Properties Methods Events 

The Subscriber object is a representation of the local video element that is playing back a remote stream. The Subscriber object includes methods that let you disable and enable local audio playback for the subscribed stream. The subscribe() method of the Session object returns a Subscriber object.

Properties

Name Type Description
element Element The HTML DOM element containing the Subscriber.
id String The DOM ID of the Subscriber.
stream Stream The stream to which you are subscribing.

Methods

Name Description
addEventListener(type, listener, context) Deprecated; use on() or once() instead.
getAudioVolume() → {Number} Returns the audio volume, between 0 and 100, of the Subscriber.
getImgData() → {String} Returns the base-64-encoded string of PNG data representing the Subscriber video.
getStats(completionHandler) Returns the details on the subscriber stream quality, including the following:
  • Total audio and video packets lost
  • Total audio and video packets received
  • Total audio and video bytes received
  • Current video frame rate
You can publish a test stream, subscribe to it (on the publishing client), and use this method to check its quality.
getStyle() → {Object} Returns an object that has the properties that define the current user interface controls of the Subscriber.
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.
removeEventListener(type, listener, context) Deprecated; use off() instead.
restrictFrameRate(value) → {Subscriber} Restricts the frame rate of the Subscriber's video stream, when you pass in true.
setAudioVolume(value) → {Subscriber} Sets the audio volume, between 0 and 100, of the Subscriber.
setPreferredFrameRate(frameRate) Sets the preferred frame rate of the subscriber's video.
setPreferredResolution(resolution) Sets the preferred resolution of the subscriber's video.
setStyle(style, value) → {Subscriber} Sets properties that define the appearance of some user interface controls of the Subscriber.
subscribeToAudio(value) → {Subscriber} Toggles audio on and off.
subscribeToVideo(value) → {Subscriber} Toggles video on and off.
videoHeight() → {Number} Returns the height, in pixels, of the Subscriber video.
videoWidth() → {Number} Returns the width, in pixels, of the Subscriber video.

addEventListener(type, listener, context)

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.

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:

getAudioVolume() → {Number}

Returns the audio volume, between 0 and 100, of the Subscriber.

Generally you use this method in conjunction with the setAudioVolume() method.

See:
Returns:
The audio volume, between 0 and 100, of the Subscriber.

getImgData() → {String}

Returns the base-64-encoded string of PNG data representing the Subscriber video.

You can use the string as the value for a data URL scheme passed to the src parameter of an image file, as in the following:

 var imgData = subscriber.getImgData();

 var img = document.createElement("img");
 img.setAttribute("src", "data:image/png;base64," + imgData);
 var imgWin = window.open("about:blank", "Screenshot");
 imgWin.document.write("<body></body>");
 imgWin.document.body.appendChild(img);
Returns:
The base-64 encoded string. Returns an empty string if there is no video.

getStats(completionHandler)

Returns the details on the subscriber stream quality, including the following:
  • Total audio and video packets lost
  • Total audio and video packets received
  • Total audio and video bytes received
  • Current video frame rate
You can publish a test stream, subscribe to it (on the publishing client), and use this method to check its quality. Based on the stream's quality, you can determine what video resolution is supported and whether conditions support video or audio. You can then publish an appropriate stream, based on the results. When using this method to test a stream published by your own client, set the testNetwork property to true in the options you pass into the Session.subscribe() method. For an example, see the opentok-network-test project on GitHub.

You may also use these statistics to have a Subscriber subscribe to audio-only if the audio packet loss reaches a certain threshold. If you choose to do this, you should set the audioFallbackEnabled setting to false when you initialize Publisher objects for the session. This prevents the OpenTok Media Router from using its own audio-only toggling implementation. (See the documentation for the OT.initPublisher() method.)

Parameters:
Name Type Description
completionHandler function A function that takes the following parameters:
  • error (Error) — Upon successful completion of the network test, this is undefined. The error results if the client is not connected or the stream published by your own client.
  • stats (Object) — An object with the following properties:

    • audio.bytesReceived (Number) — The total number of audio bytes received by the subscriber
    • audio.packetsLost (Number) — Total audio packets that did not reach the subscriber
    • audio.packetsReceived (Number) — The total number of audio packets received by the subscriber
    • timestamp (Number) — The timestamp, in milliseconds since the Unix epoch, for when these stats were gathered
    • video.bytesReceived (Number) — The total video bytes received by the subscriber
    • video.packetsLost (Number) — The total number of video packets that did not reach the subscriber
    • video.packetsReceived (Number) — The total number of video packets received by the subscriber
    • video.frameRate (Number) — The current video frame rate

getStyle() → {Object}

Returns an object that has the properties that define the current user interface controls of the Subscriber. You can modify the properties of this object and pass the object to the setStyle() method of the Subscriber object. (See the documentation for setStyle() to see the styles that define this object.)
See:
Returns:
The object that defines the styles of the Subscriber.

off(type, handler, context) → {Object}

Removes an event handler or handlers.

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().)
See:
Returns:
The object that dispatched the event.

on(type, handler, context) → {EventDispatcher}

Adds an event handler function for one or more events.

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.
See:
Returns:
The EventDispatcher object.

once(type, handler, context) → {Object}

Adds an event handler function for one or more events. Once the handler is called, the specified handler method is removed as a handler for this event. (When you use the 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.
See:
Returns:
The object that dispatched the event.

removeEventListener(type, listener, context)

Deprecated; use off() instead.

Removes an event listener for a specific event.

Throws an exception if the listener name is invalid.

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:

restrictFrameRate(value) → {Subscriber}

Restricts the frame rate of the Subscriber's video stream, when you pass in true. When you pass in false, the frame rate of the video stream is not restricted.

When the frame rate is restricted, the Subscriber video frame will update once or less per second.

This feature is only available in sessions that use the OpenTok Media Router (sessions with the 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:

  • It reduces CPU usage.
  • It reduces the network bandwidth consumed.
  • It lets you subscribe to more streams simultaneously.

Reducing a subscriber's frame rate has no effect on the frame rate of the video in other clients.

Parameters:
Name Type Description
value Boolean Whether to restrict the Subscriber's video frame rate (true) or not (false).
Returns:
The Subscriber object. This lets you chain method calls, as in the following:
mySubscriber.restrictFrameRate(false).subscribeToAudio(true);

setAudioVolume(value) → {Subscriber}

Sets the audio volume, between 0 and 100, of the Subscriber.

You can set the initial volume when you call the Session.subscribe() method. Pass a audioVolume property of the properties parameter of the method.

Parameters:
Name Type Description
value Number The audio volume, between 0 and 100.
See:
Returns:
The Subscriber object. This lets you chain method calls, as in the following:
mySubscriber.setAudioVolume(50).setStyle(newStyle);

setPreferredFrameRate(frameRate)

Sets the preferred frame rate of the subscriber's video. This method is part of the subscriber quality preference beta feature. For more infomation, see the OpenTok Beta Programs page.

Lowering the preferred frame rate lowers video quality on the subscribing client, but it also reduces network and CPU usage. You may want to use a lower frame rate for a subscriber to a stream that is less important than other streams.

Not every frame rate is available to a subscriber. When you set the preferred frame rate for the subscriber, OpenTok.js picks the best frame rate available that matches your setting. The frame rates available are based on the value of the Subscriber object's stream.frameRate property, which represents the maximum value available for the stream. The actual frame rates available depend, dynamically, on network and CPU resources available to the publisher and subscriber.

You can set the initial preferred frame rate used by setting the preferredFrameRate property of the options object you pass into the Session.subscribe() method.

Parameters:
Name Type Description
frameRate Number Set this to the desired frame rate (in frames per second). Set this to null to remove the preferred frame rate, and the client will use the highest frame rate available.
See:

setPreferredResolution(resolution)

Sets the preferred resolution of the subscriber's video. This method is part of the subscriber quality preference beta feature. For more infomation, see the OpenTok Beta Programs page.

Lowering the preferred resolution lowers video quality on the subscribing client, but it also reduces network and CPU usage. You may want to use a lower resolution based on the dimensions of subscriber's video on the web page. You may want to use a resolution rate for a subscriber to a stream that is less important (and smaller) than other streams.

Not every frame rate is available to a subscriber. When you set the preferred resolution for the subscriber, OpenTok.js picks the best resolution available that matches your setting. The resolutions available are based on the value of the Subscriber object's stream.resolution property, which represents the maximum resolution available for the stream. The actual resolutions available depend, dynamically, on network and CPU resources available to the publisher and subscriber.

You can set the initial preferred resolution used by setting the preferredResolution property of the options object you pass into the Session.subscribe() method.

Parameters:
Name Type Description
resolution Object Set this to an object with two properties: width and height (both numbers), such as {width: 320, height: 240}. Set this to null to remove the preferred resolution, and the client will use the highest resolution available.
See:

setStyle(style, value) → {Subscriber}

Sets properties that define the appearance of some user interface controls of the Subscriber.

You can either pass one parameter or two parameters to this method.

If you pass one parameter, style, it is an object that has the following properties:

  • audioLevelDisplayMode (String) — How to display the audio level indicator. Possible values are: "auto" (the indicator is displayed when the video is disabled), "off" (the indicator is not displayed), and "on" (the indicator is always displayed).
  • 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 Publisher object). You can pass an http or https URI to a PNG, JPEG, or non-animated GIF file location. You can also use the data URI scheme (instead of http or https) and pass in base-64-encrypted PNG data, such as that obtained from the Subscriber.getImgData() method (for example, you could call mySubscriber.setStyle("backgroundImageURI", mySubscriber.getImgData())). If the URL or the image data is invalid, the property is ignored (the attempt to set the image fails silently).
  • buttonDisplayMode (String) — How to display the 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 always 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 always displayed).
  • videoDisabledDisplayMode (String) — Whether to display the video disabled indicator and video disabled warning icons for a Subscriber. These icons indicate that the video has been disabled (or is in risk of being disabled for the warning icon) due to poor stream quality. Possible values are: "auto" (the icons are automatically when the displayed video is disabled or in risk of being disabled due to poor stream quality), "off" (do not display the icons), and "on" (display the icons).

For example, the following code passes one parameter to the method:

mySubscriber.setStyle({nameDisplayMode: "off"});

If you pass two parameters, style and value, they are key-value pair that define one property of the display style. For example, the following code passes two parameter values to the method:

mySubscriber.setStyle("nameDisplayMode", "off");

You can set the initial settings when you call the Session.subscribe() method. Pass a style property as part of the properties parameter of the method.

The OT object dispatches an exception event if you pass in an invalid style to the method. The code property of the ExceptionEvent object is set to 1011.

Parameters:
Name Type Description
style Object Either an object containing properties that define the style, or a String defining this single style property to set.
value String The value to set for the style passed in. Pass a value for this parameter only if the value of the style parameter is a String.

See:
Returns:
The Subscriber object.

subscribeToAudio(value) → {Subscriber}

Toggles audio on and off. Starts subscribing to audio (if it is available and currently not being subscribed to) when the value is true; stops subscribing to audio (if it is currently being subscribed to) when the value is false.

Note: This method only affects the local playback of audio. It has no impact on the audio for other connections subscribing to the same stream. If the Publisher is not publishing audio, enabling the Subscriber audio will have no practical effect.

Parameters:
Name Type Description
value Boolean Whether to start subscribing to audio (true) or not (false).
See:
Returns:
The Subscriber object. This lets you chain method calls, as in the following:
mySubscriber.subscribeToAudio(true).subscribeToVideo(false);

subscribeToVideo(value) → {Subscriber}

Toggles video on and off. Starts subscribing to video (if it is available and currently not being subscribed to) when the value is true; stops subscribing to video (if it is currently being subscribed to) when the value is false.

Note: This method only affects the local playback of video. It has no impact on the video for other connections subscribing to the same stream. If the Publisher is not publishing video, enabling the Subscriber video will have no practical effect.

Parameters:
Name Type Description
value Boolean Whether to start subscribing to video (true) or not (false).
See:
Returns:
The Subscriber object. This lets you chain method calls, as in the following:
mySubscriber.subscribeToVideo(true).subscribeToAudio(false);

videoHeight() → {Number}

Returns the height, in pixels, of the Subscriber video.
Returns:
the width, in pixels, of the Subscriber video.

videoWidth() → {Number}

Returns the width, in pixels, of the Subscriber video.
Returns:
the width, in pixels, of the Subscriber video.

Events

audioLevelUpdated

Dispatched periodically to indicate the subscriber's audio level. The event is dispatched up to 60 times per second, depending on the browser. The audioLevel property of the event is audio level, from 0 to 1.0. See AudioLevelUpdatedEvent for more information.

The following example adjusts the value of a meter element that shows volume of the subscriber. Note that the audio level is adjusted logarithmically and a moving average is applied:

var movingAvg = null;
subscriber.on('audioLevelUpdated', function(event) {
  if (movingAvg === null || movingAvg <= event.audioLevel) {
    movingAvg = event.audioLevel;
  } else {
    movingAvg = 0.7 * movingAvg + 0.3 * event.audioLevel;
  }

  // 1.5 scaling to map the -30 - 0 dBm range to [0,1]
  var logLevel = (Math.log(movingAvg) / Math.LN10) / 1.5 + 1;
  logLevel = Math.min(Math.max(logLevel, 0), 1);
  document.getElementById('subscriberMeter').value = logLevel;
});

This example shows the algorithm used by the default audio level indicator displayed in an audio-only Subscriber.

See:

connected

Sent when the subscriber's stream has resumed, after the Subscriber dispatches a disconnected event.
See:

destroyed

Dispatched when the Subscriber element is removed from the HTML DOM. When this event is dispatched, you may choose to adjust or remove HTML DOM elements related to the subscriber.

To prevent the Subscriber from being removed from the DOM when the stream is destroyed, listen for the streamDestroyed event dispatched by the Session object. The streamDestroyed event dispatched by the Session object is cancelable, and calling the preventDefault() method of the event object prevents Subscribers of the stream from being removed from the HTML DOM.

See:

disconnected

Sent when the subscriber's stream has been interrupted.

In response to this event, you may want to provide a user interface notification, to let the user know that the audio-video stream is temporarily disconnected and that the app is trying to reconnect to it.

If the client reconnects to the stream, the Subscriber object dispatches a connected event. Otherwise, if the client cannot reconnect to the stream, the Subscriber object dispatches a destroyed event.

See:

videoDimensionsChanged

Dispatched when the video dimensions of the video change. This can occur when the stream.videoType property is set to "screen" (for a screen-sharing video stream), when the user resizes the window being captured. It can also occur if the video is being published by a mobile device and the user rotates the device (causing the camera orientation to change). This event object has a newValue property and an oldValue property, representing the new and old dimensions of the video. Each of these has a height property and a width property, representing the height and width, in pixels.
See:

videoDisabled

Dispatched when the video for the subscriber is disabled.

The reason property defines the reason the video was disabled. This can be set to one of the following values:

  • "publishVideo" — The publisher stopped publishing video by calling publishVideo(false).
  • "quality" — The OpenTok Media Router stopped sending video to the subscriber based on stream quality changes. This feature of the OpenTok Media Router has a subscriber drop the video stream when connectivity degrades. (The subscriber continues to receive the audio stream, if there is one.)

    Before sending this event, when the Subscriber's stream quality deteriorates to a level that is low enough that the video stream is at risk of being disabled, the Subscriber dispatches a videoDisableWarning event.

    If connectivity improves to support video again, the Subscriber object dispatches a videoEnabled event, and the Subscriber resumes receiving video.

    By default, the Subscriber displays a video disabled indicator when a videoDisabled event with this reason is dispatched and removes the indicator when the videoEnabled event with this reason is dispatched. You can control the display of this icon by calling the setStyle() method of the Subscriber, setting the videoDisabledDisplayMode property(or you can set the style when calling the Session.subscribe() method, setting the style property of the properties parameter).

    This feature is only available in sessions that use the OpenTok Media Router (sessions with the media mode set to routed), not in sessions with the media mode set to relayed.

    You can disable this audio-only fallback feature, by setting the audioFallbackEnabled property to false in the options you pass into the OT.initPublisher() method on the publishing client. (See OT.initPublisher().)

  • "subscribeToVideo" — The subscriber started or stopped subscribing to video, by calling subscribeToVideo(false).

See:

videoDisableWarning

Dispatched when the OpenTok Media Router determines that the stream quality has degraded and the video will be disabled if the quality degrades more. If the quality degrades further, the Subscriber disables the video and dispatches a videoDisabled event.

By default, the Subscriber displays a video disabled warning indicator when this event is dispatched (and the video is disabled). You can control the display of this icon by calling the setStyle() method and setting the videoDisabledDisplayMode property (or you can set the style when calling the Session.subscribe() method and setting the style property of the properties parameter).

This feature is only available in sessions that use the OpenTok Media Router (sessions with the media mode set to routed), not in sessions with the media mode set to relayed.

See:

videoDisableWarningLifted

Dispatched when the OpenTok Media Router determines that the stream quality has improved to the point at which the video being disabled is not an immediate risk. This event is dispatched after the Subscriber object dispatches a videoDisableWarning event.

This feature is only available in sessions that use the OpenTok Media Router (sessions with the media mode set to routed), not in sessions with the media mode set to relayed.

See:

videoElementCreated

Dispatched when the Subscriber's video element is created. Add a listener for this event when you set the insertDefaultUI option to false in the call to the Session.subscribe() method. The element property of the event object is a reference to the Subscriber's video element (or in Internet Explorer the object element containing the video). Add it to the HTML DOM to display the video. When you set the insertDefaultUI option to false, the video (or object) element is not automatically inserted into the DOM.

Add a listener for this event only if you have set the insertDefaultUI option to false. If you have not set insertDefaultUI option to false, do not move the video (or object) element in in the HTML DOM. Doing so causes the Subscriber object to be destroyed.

See:

videoEnabled

Dispatched when the OpenTok Media Router resumes sending video to the subscriber after video was previously disabled.

The reason property defines the reason the video was enabled. This can be set to one of the following values:

  • "publishVideo" — The publisher started publishing video by calling publishVideo(true).
  • "quality" — The OpenTok Media Router resumed sending video to the subscriber based on stream quality changes. This feature of the OpenTok Media Router has a subscriber drop the video stream when connectivity degrades and then resume the video stream if the stream quality improves.

    This feature is only available in sessions that use the OpenTok Media Router (sessions with the media mode set to routed), not in sessions with the media mode set to relayed.

  • "subscribeToVideo" — The subscriber started or stopped subscribing to video, by calling subscribeToVideo(false).

To prevent video from resuming, in the videoEnabled event listener, call subscribeToVideo(false) on the Subscriber object.

See: