Publisher class

The Publisher object provides the mechanism through which control of the published stream is accomplished. Calling the TB.initPublisher method of a Session object creates a Publisher object.

The following code instantiates a session, and publishes an audio-video stream upon connection to the session:

var API_KEY = ""; // Replace with your API key. See https://dashboard.tokbox.com/projects
var sessionID = ""; // Replace with your own session ID.
                    // See https://dashboard.tokbox.com/projects
var token = ""; // Replace with a generated token that has been assigned the moderator role.
                // See https://dashboard.tokbox.com/projects

var session = TB.initSession(sessionID);
session.addEventListener("sessionConnected", sessionConnectHandler);
session.connect(API_KEY, token);

function sessionConnectHandler(event) {
    var div = document.createElement('div');
    div.setAttribute('id', 'publisher');
    
    var publisherContainer = document.getElementById('publisherContainer');  
        // This example assumes that a publisherContainer div exists
    publisherContainer.appendChild(div);

    var publisherProperties = {width: 400, height:300, name:"Bob's stream"};
    publisher = TB.initPublisher(API_KEY, 'publisher', publisherProperties);
    session.publish(publisher);
}

This example creates a Publisher object and adds its video to a DOM element named publisher by calling the TB.initPublisher() method. It then publishes a stream to the session by calling the publish() method of the Session object.

See

TB.initPublisher

Session.publish()

Publisher properties

Publisher objects have the following properties:

id (String) — The ID of the DOM element through which the Publisher stream is displayed on the local web page.

session (Session) — The Session to which the Publisher is publishing a stream. If the Publisher isn't publishing a stream to a Session, this property is set to null. For example, if the Publisher was created by calling TB.initPublisher but it has not been passed to the publish() method of a Session object, the property is set to null. When you pass the Publisher to the publish() method of a Session object, this property is set to that Session object.

replaceElementId (String) — The ID of the DOM element that was replaced when the Publisher video stream was inserted into the local web page.

Note: Publisher properties should only be used as read-only entities. The results of using JavaScript to directly change the values of Publisher properties will be unpredictable.

Publisher methods

Publisher objects have the following methods.

Method Description
addEventListener(eventType:String, listener:Function) Registers a method as an event listener for a specific event.
destroy() Deletes the Publisher and removes it from the HTML DOM.
detectDevices() Detect connected cameras and microphones available to the Publisher.
detectMicActivity(value:Boolean) When set to true, causes the Publisher to dispatch microphoneActivityLevel events.
disableMicrophone() Deprecated in OpenTok v0.91.9. Use the publishAudio() method.
enableMicrophone() Deprecated in OpenTok v0.91.9. Use the publishAudio() method.
getEchoCancellationMode():String Returns a string corresponding to the echo cancellation mode of the Publisher.
getImgData():String Returns a base-64-encoded string of PNG data representing the Publisher video.
getMicrophoneGain():Number Gets the microphone gain, between 0 and 100, of the Publisher.
getStyle():Object Gets an object that has properties that define the current appearance of user interface controls of the Publisher.
publishAudio(value:Boolean) Starts publishing audio (if it is currently not being published) when the value is true; stops publishing audio (if it is currently being published) when the value is false.
publishVideo(value:Boolean) Starts publishing video (if it is currently not being published) when the value is true; stops publishing video (if it is currently being published) when the value is false.
removeEventListener(eventType:String, listener:Function) Removes an event listener for a specific event.
setCamera(name:String):Publisher Sets the Camera to be used by the Publisher, based on the camera name.
setMicrophone(name:String):Publisher Sets the microphone to be used by the Publisher, based on the microphone name.
setMicrophoneGain(value:Number):Publisher Sets the microphone gain, between 0 and 100, of the Publisher.
setStyle(style:Object, [value:Object]):Publisher Sets properties that define the appearance of some user interface controls of the Publisher.

addEventListener(type:String, listener:Function)

Registers a method as an event listener for a specific event.

Parameters

type (String) — This string identifying the type of event. See Publisher events.

listener (Function) — The function to be invoked when the Publisher object dispatches the event.

Example — resize event

The following example registers a function, publisherResizeHandler() as the event handler for resize events. The Publisher object dispatches this event when the video object must resize due to the appearance of the Flash Player Settings dialog box.

var div = document.createElement('div');
div.setAttribute('id', 'publisher');
var publisherContainer = document.getElementById('publisherContainer');
publisherContainer.appendChild(div);
publisher = TB.initPublisher(API_KEY, 'publisher');
session.publish(publisher);
					
publisher.addEventListener("resize", publisherResizeHandler);

function publisherResizeHandler(event) {
    newWidth = event.widthTo;
    newHeight = event.heightTo;
    // Modify the UI based on the new dimensions of the publisher 
}

Example — settingsButtonClick event

The following example registers a function, settingsButtonClickHandler() as the event handler for settingsButtonClick events. The Publisher object dispatches this event when the user clicks the button in the publisher video. (To view this button, mouse over the lower-right corner of the publisher video.)

var div = document.createElement('div');
div.setAttribute('id', 'publisher');
var publisherContainer = document.getElementById('publisherContainer');
publisherContainer.appendChild(div);
publisher = TB.initPublisher(API_KEY, 'publisher');
session.publish(publisher);
					
publisher.addEventListener("settingsButtonClick", settingsButtonClickHandler);

function settingsButtonClickHandler(event) {
    manageDevices();
}
function manageDevices() {
    deviceManager = TB.initDeviceManager(apiKey);
    deviceManager.displayPanel("deviceManagerContainer", publisher);
}

For another code example that uses the settingsButtonClick event, see DeviceManager Example.

destroy()

Deletes the Publisher object and removes it from the HTML DOM.

detectDevices()

Has the OpenTok API detect available cameras and microphones. This operation is asynchronous. The Publisher object dispatches a devicesDetected event when it detects the available devices.

The following example uses the detectDevices() method to check for available cameras and microphones.

var cameras;
var mics;

var publisher = TB.initPublisher(API_KEY);
publisher.addEventListener("devicesDetected", devicesDetectedHandler);
publisher.detectDevices();

function devicesDetectedHandler(event) {
    cameras = event.cameras;
    mics = event.microphones;

    if (event.cameras.length < 1) {
        alert ("No camera connected.");
    } else if (event.microphone.length < 1) {
        alert ("No microphone connected.");
    }
    if (event.cameras.length > 0 && event.microphones.length > 0) {
        alert("Selected camera: " + event.selectedCamera.name + "\nSelected microphone: " + selectedMicrophone.name);
    }
}

Your app may use the cameras and microphones properties of the event to build user interface controls (such as a drop-down list) in which the user can select a camera and a microphone to attach to the Publisher object. (See setMicrophone() and setCamera().)

Returns

The Publisher object.

detectMicActivity(value:Boolean)

Causes the Publisher object to start or stop dispatching microphoneActivityLevel events, based on the value you pass in: true (start) or (false (stop). The microphoneActivityLevel event includes a value property which is the representative microphone level, from -1 to 100, at the time of the event. A value of -1 indicates an inactive microphone; 0 indicates a silent microphone, 100 indicates full activity.

Use this method and the microphoneActivityLevel event to adjust the microphone level of the Publisher. For example, you can create an visual display of the value property, and have the client adjust the mic level based on that display.

Important: Calling detectMicActivity(true) while publishing can diminish the frame rate of the displayed video. When you are done detecting the microphone activity level of the Publisher, stop the event by calling detectMicActivity(false).

The following example uses the detectMicActivity() method to get microphone levels.

var publisher = TB.initPublisher(API_KEY);
publisher.addEventListener("microphoneActivityLevel", micActivityHandler);
publisher.detectMicActivity(true);

function micActivityHandler(event) {
    // In this event handler, you might adjust a user interface control
    // to show the user the microphone level, based on the value property
    // of the event object.
}

Parameters

value (Boolean) — Whether the Publisher will start (true) or stop (false) dispatching microphoneActivityLevel events.

Returns

The Publisher object.

disableMicrophone()

Deprecated in OpenTok v0.91.9. Use the publishAudio() method, and set the value parameter to false.

enableMicrophone()

Deprecated in OpenTok v0.91.9. Use the publishAudio() method, and set the value parameter to true.

getEchoCancellationMode():String

Returns a string corresponding to the echo cancellation mode of the Publisher. The string can be one of the following values:

  • "unknown" — The echo cancellation mode is unknown (the initial state).
  • "none" — The Publisher is not using acoustic echo cancellation.
  • "fullDuplex — The Publisher is using acoustic echo cancellation.

You should call this method after the Publisher dispatches the echoCancellationModeChanged event. Until this event is dispatched, the Publisher will not use echo cancellation; however, the method returns "unknown" (not "none") until the event is dispatched.

The Publisher dispatches the echoCancellationModeChanged event after the Publisher is first created (by calling the publish() method) when the TokBox code can determine the correct echo cancellation mode. After that, the Publisher dispatches the event again whenever the setting changes. The setting may change because of the following reasons:

  • The user switches to a microphone that changes the setting. (For example, the user switches from a USB mic, which does not support AEC, to a mic that supports AEC — or vice versa.)
  • Device Panel is opened or closed, changing the setting. (For example, the Publisher is using a microphone that supports AEC, and the Device Panel is displayed, which disables AEC for the mic. When the Device Panel is closed, the Publisher dispatches the event again, indicating that the Publisher is once again in AEC mode.)
  • A new Publisher that publishes audio is added, which changes the echo cancellation mode to "none" (if it is not already that).
  • A Publisher that publishes audio is removed so that there is now only one Publisher, which may change the echo cancellation mode to "fullDuplex" (if acoustic echo suppression is supported).

A Publisher will not use acoustic echo cancellation if any of the following is true:

  • The Publisher uses a USB microphone. (Acoustic echo cancellation is not supported for USB microphones.)
  • The client is publishing audio in another Publisher.
  • The user has prevented storage of Flash Player local shared objects.

If a Publisher does not use acoustic echo cancellation, it may echo back a subscribed audio stream. Use this method, along with the echoCancellationModeChanged, to configure your app in the case where acoustic echo cancellation is not supported.

getImgData():String

Returns a base-64-encoded string of PNG data representing the Publisher video. Returns an empty string if there is no 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 = publisher.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);

getMicrophoneGain():Number

Returns the microphone gain, between 0 and 100, of the Publisher.

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

See the setMicrophoneGain() method.

getStyle():Object

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

Returns

The object that defines the styles of the Publisher.

See

setStyle()

publishAudio(value:Boolean)

Starts publishing audio (if it is currently not being published) when the value is true; stops publishing audio (if it is currently being published) when the value is false.

Note: Prior to calling the publishAudio() method, set the showAudioSettings property of a DeviceManager object to false if you are publishing in video-only mode.

Parameters

value (Boolean) — Whether to start publishing audio (true) or not (false).

publishVideo(value:Boolean)

Starts publishing video (if it is currently not being published) when the value is true; stops publishing video (if it is currently being published) when the value is false.

Note: Prior to calling the publishVideo method, set the showVideoSettings property of a DeviceManager object to false if you are publishing in audio-only mode.

Parameters

value (Boolean) — Whether to start publishing video (true) or not (false).

removeEventListener(type:String, listener:Function)

Removes an event listener for a specific event.

Parameters

type (String) — The string identifying the type of event.

listener (Function) — The event listener function to remove.

The TB object throws an exception if the listener name is invalid.

See

addEventListener()

setCamera(name:String):Publisher

Sets the camera to be used by the Publisher, based on the camera name.

You can get an array of available camera by calling the detectDevices() method; the Publisher object dispatches a devicesDetected event in response to calling this method. The devicesDetected event object includes a cameras property, which is an array of available cameras. Each element in the array has a name property, which you can use to pass into the setCamera() method.

Parameters

name (Number) — The camera name.

Returns

The Publisher object. This lets you chain method calls, as in the following:

myPublisher.setMicrophone(micName).setCamera(cameraName);

See

detectDevices()

setMicrophone()

setMicrophone(name:String):Publisher

Sets the microphone to be used by the Publisher, based on the microphone name.

You can get an array of available microphones by calling the detectDevices() method. The Publisher dispatches a devicesDetected event in response to calling this method. The devicesDetected event object includes a microphones property, which is an array of available microphones. Each element in the array has a name property, which you can use to pass into the setMicrophone() method.

Parameters

name (Number) — The microphone name.

Returns

The Publisher object. This lets you chain method calls, as in the following:

myPublisher.setCamera(cameraName).setMicrophone(micName);

See

detectDevices()

setCamera()

setMicrophoneGain(value:Number):Publisher

Sets the microphone gain, between 0 and 100, of the Publisher.

You can set the initial microphone gain when you call the Session.publish() or TB.initPublisher() method. Pass a microphoneGain property of the properties parameter of the method.

Parameters

value (Number) — The microphone gain value.

Returns

The Publisher object. This lets you chain method calls, as in the following:

myPublisher.setMicrophoneGain(50).setStyle(newStyle);

See

getMicrophoneGain()

Session.publish()

TB.initPublisher()

setStyle(style:Object, [value:String]):Publisher

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

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 that define the style:

  • 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 publisherVideo(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 Publisher.getImgData() method. For example, you could set the property to "data:VBORw0KGgoAA...", where the portion of the string after "data:" is the result of a call to Publisher.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 microphone controls and settings buttons. Possible values are: "auto" (buttons are displayed when the stream is first displayed and when the user mouses over the display), "off" (buttons are not displayed), and "on" (buttons are displayed). The showMicButton and showSettingsButton properties define whether each individual control is displayed.
  • nameDisplayMode (String) — Whether to display the stream name. Possible values are: "auto" (the name is displayed when the stream is first displayed and when the user mouses over the display), "off" (the name is not displayed), and "on" (the name is displayed).
  • showMicButton (Boolean) — Whether to display the microphone controls.
  • showSettingsButton (Boolean) — Whether to display the settings buttons.

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

var newStyle = {
        buttonDisplayMode: "auto",
        nameDisplayMode: "off",
        showMicButton: true,
        showSettingsButton: true,
        showCameraToggleButton: true
    }
myPublisher.setStyle(newStyle);

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 each call of the method:

myPublisher.setStyle("buttonDisplayMode", "auto");
myPublisher.setStyle("nameDisplayMode", "on");

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

Parameters

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.

Returns

The Publisher object. This lets you chain method calls, as in the following:

myPublisher.setStyle(newStyle).setMicGain(50);

Event

The TB 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.

See

getStyle()

Session.publish()

TB.initPublisher()

Publisher events

A Publisher object can dispatch the following events:

Event type Event class Description
"accessAllowed" Event The user has clicked the Allow button in the Flash Player Settings dialog box, granting the app access to the camera and microphone.
"accessDenied" Event The user has clicked the Deny button in the Flash Player Settings dialog box, preventing the app from having access to the camera and microphone.
"accessDialogClosed" Event The Flash Player Settings dialog box closed. (This is the dialog box in which the user can grant the app access to the camera and microphone.)
"accessDialogOpened" Event The Flash Player Settings dialog box has opened. (This is the dialog box in which the user can grant the app access to the camera and microphone.)
"deviceInactive" DeviceEvent The camera or microphone used has become inactive. If a camera or microphone attached to a publisher is initially inactive, the Publisher immediately dispatches a deviceInactive event. Also, when a camera or microphone is disconnected, the Publisher object dispatches the deviceInactive event.
"devicesDetected" DeviceStatusEvent A Publisher object dispatches a devicesDetected event in response to calling the detectDevices() method. The event includes a cameras property and a microphones property, which are arrays of available cameras and microphones.

To check whether a user has available cameras and other requirements for publishing, check the capabilities property of the Session object.

For an example of using this event, see detectDevices().
"echoCancellationModeChanged" Event The echo cancellation mode of the Publisher has changed. See the documentation for the getEchoCancellationMode method.
"invalidDeviceName" DeviceEvent You specified an invalid name for the microphoneName or cameraName property of the properties parameter of Session.publish() or TB.initPublisher(). See Session.publish() and TB.initPublisher().
"microphoneActivityLevel" ValueEvent A Publisher object dispatches a microphoneActivityLevel event in response to calling detectMicActivity(true) on a Publisher object. The event includes a value property which is the representative microphone level, from -1 to 100, at the time of the event. A value of 0 indicates silence, and 100 indicated full volume. A value of -1 indicates an inactive microphone.

For an example of using this event, see detectMicActivity().

"microphoneGainChanged" ValueEvent A Publisher object dispatches a microphoneGainChanged event when the microphone gain changes (because of the user adjusting the microphone gain or as a result of calling the setMicrophoneGain() method of the Publisher object). The event includes a value property which is the microphone gain, from 0 (muted) to 100 (full gain).
"resize" ResizeEvent The Flash Player settings dialog box is being displayed, and the HTML element containing the video must be resized to fit the entire dialog box. The Publisher object dispatches this event only if the HTML element is smaller than 215 x 138 pixels.
"settingsButtonClick" Event The user has clicked the button in the publisher video. (To view this button, mouse over the lower-right corner of the publisher video window.) The default behavior for this event is to display the display panel in the center of the HTML page. (See Event.preventDefault().)

IRC Live Chat

Have a quick question? Chat with TokBox Support on IRC. Join chat