Have you explored the newest version of the OpenTok platform? Check out OpenTok 2.0, built on top of WebRTC. Learn more

StreamEvent class

StreamEvent is an event that can have type "streamCreated" or "streamDestroyed". These events are dispatched when a client starts or stops publishing to a Session. This includes remote clients publishing on the session as well as the local client publishing to the session. Properties of StreamEvent include:

StreamEvent properties

The StreamEvent object has the following properties:

cancelable (Boolean) — Whether the event has a default behavior that is cancelable (true) or not (false). You can cancel the default behavior by calling the preventDefault() method of the StreamEvent object in the event listener function. The streamDestroyed event is cancelable. (See preventDefault().)

streams (Array[Stream]) — An array of Stream objects corresponding to the streams to which this event refers. This is usually an array containing only one Stream object, corresponding to the stream that was added (in the case of a streamCreated event) or deleted (in the case of a streamDestroyed event). However, the array may contain multiple Stream objects if multiple streams were added or deleted. A stream may be published by the local client or another client connected to the session.

reason (String) — For a streamDestroyed event, a description of why the session disconnected. This property can have one of the following values:

  • "clientDisconnected" — A client disconnected from the session by calling the disconnect() method of the Session object or by closing the browser. (See Session.disconnect().)
  • "forceDisconnected" — A moderator has disconnected the publisher of the stream from the session, by calling the forceDisconnect() method of the Session object. (See Session.forceDisconnect().)
  • "forceUnpublished" — A moderator has forced the publisher of the stream to stop publishing the stream, by calling the forceUnpublish() method of the Session object. (See Session.forceUnpublish().)
  • "networkDisconnected" — The network connection terminated abruptly (for example, the client lost their internet connection).
  • "streamNotRecording" — The stream is not being recorded to the specified archive.
  • "streamRecordingInProgress" — The stream is already being recorded to the specified archive.
  • "streamRecordingStarted" — The stream is being recorded to an archive.
  • "streamRecordingStopped" — The stream has stopped being recorded to an archive.

Depending on the context, this description may allow the developer to refine the course of action they take in response to an event.

For a streamCreated event, this string is undefined.

target (Object) — The object that dispatched the event.

type (String) — The type of event. The StreamEvent object defines the following types of events:

  • "streamCreated" — A new stream has been created.
  • "streamDestroyed" — A stream has ended.

StreamEvent methods

The StreamEvent object has the following methods:

isDefaultPrevented():Boolean — Whether the default event behavior has been prevented via a call to preventDefault() (true) or not (false). See preventDefault().

preventDefault() — Prevents the default behavior associated with the event from taking place.

For the streamDestroyed event, if the reason is set to "forceDisconnected" or networkDisconnected, the default behavior is that all Subscriber objects that are subscribed to the stream are unsubscribed (and 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, optionally, clean up Subscriber objects using your own code. See Session.getSubscribersForStream().

If the reason property is set to "forceUnpublished", the default behavior is that the associated Subscriber or Publisher objects corresponding with the stream are unsubscribed or unpublished (and 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, optionally, clean up Subscriber or Publisher objects using your own code. See Session.getPublisherForStream() and Session.getSubscribersForStream().

Call the preventDefault() method in the event listener function for the event.

Example — streamCreated event

The following code initializes a session and sets up an event listener for when a stream is created:

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

var session = TB.initSession(sessionID);
session.addEventListener("streamCreated", streamCreatedHandler);
session.connect(apiKey, token);

function streamCreatedHandler(event) {
    for (var i = 0; i < event.streams.length; i++) {
        // Only display others' streams, not those that the client publishes.
        if (event.streams[i].connection.connectionId != event.target.connection.connectionId) {
               displayStream(stream);
        }
    }
}

function displayStream(stream) {
    var div = document.createElement('div');
    div.setAttribute('id', 'stream' + stream.streamId);
    
    var streamsContainer = document.getElementById('streamsContainer');
    streamsContainer.appendChild(div);
    
    var divProps = {width: 400, height:300, audioEnabled:true};			
    subscriber = session.subscribe(stream, 'stream' + stream.streamId, divProps);
}

For this example, in addition to the event handler for the streamCreated event, you would probably want to create an event handler for the sessionConnected event. This event handler can display the streams that are present when the session first connects. See SessionConnectEvent.

Example — streamDestroyed event

The following code initializes a session and sets up an event listener for when a stream ends:

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

var session = TB.initSession(sessionID);
session.addEventListener("streamDestroyed", streamDestroyedHandler);
session.connect(apiKey, token);

function streamDestroyedHandler(event) {
    for (var i = 0; i < event.streams.length; i++) {
        var stream = event.streams[i];
        alert("Stream " + stream.name + " ended. " + event.reason); 
        unsubscribe(stream);
    }
}
function unsubscribe(stream) {
	var subscribers = session.getSubscribersForStream(stream);
	for (var i = 0; i < subscribers.length; i++) {
		session.unsubscribe(subscribers[i]);
	}
}

IRC Live Chat

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