JavaScript Tutorial — Recording stand-alone archives

This tutorial shows how to use the OpenTok JavaScript library to record and play back stand-alone archives. A stand-alone archive is a recording of an audio-video stream that you make outside of an OpenTok session. You can then play the stand-alone archive on its own (outside of a session); or you can play it back in an OpenTok session, so that all connected clients can view it.

The OpenTok archiving API is in beta testing. For more information, see the Archiving overview.

Download the source code.

Testing the tutorial online

 

  1. Open the page in a browser.
  2. When you first open the page, it displays the OpenTok Recorder, which lets you create stand-alone recordings.

    If the Flash Player Settings dialog box is displayed, click the Allow button and then click the Close button. This grants tokbox.com access to your camera and microphone.

  3. Click the red Record button at the bottom of the Recorder.
  4. You are now recording a stand-alone archive.

  5. Wait at least 10 seconds, and then click the Stop button at the bottom of the Recorder.
  6. Click the Save button at the bottom of the Recorder.
  7. The OpenTok library saves the archive to the OpenTok servers. A screenshot of the recording appears below the Recorder.

  8. Click the screenshot of the recording.
  9. The archive plays back in the OpenTok stand-alone archive Player.

Testing the code on your own computer

See the instructions in the Hello World tutorial.

Understanding the code

Note: You may want to look at the Basic Tutorial sample, if you have not already. It provides details on many of the basic concepts, like connecting to an OpenTok session, publishing an audio-video stream, and subscribing to streams.

To understand how the OpenTok JavaScript library is used, view the source for this browser page. You can also download the source for this Tutorial application (and for the other OpenTok tutorial applications) by clicking the Download Source link at the top of this page.

Recording stand-alone archives

First, instantiate a RecorderManager object by calling TB.initRecorderManager(). The init() function in the page does this when the page is loaded:

recorderManager = TB.initRecorderManager(API_KEY);

The RecorderManager object lets you add an OpenTok Recorder or an OpenTok Player to your page. The createRecorder() function adds a Recorder to the page by calling the displayRecorder() method of the RecorderManager object.

var TOKEN = ""; // Replace with a generated token that has been assigned the moderator role.
                // See https://dashboard.tokbox.com/projects

function createRecorder() {
    var recDiv = document.createElement('div');
    recDiv.setAttribute('id', 'recorderElement');
    document.getElementById('recorderContainer').appendChild(recDiv);
    recorder = recorderManager.displayRecorder(TOKEN, recDiv.id);
    recorder.addEventListener('recordingStarted', recStartedHandler);
    recorder.addEventListener('archiveSaved', archiveSavedHandler);
}

First the code creates a DIV element that will be replaced by the OpenTok Recorder and adds it as a child of the 'recorderContainer' element. Then the code calls the displayRecorder() method of the RecorderManager object. The first parameter is an OpenTok token string. The token must include the "moderator" role to successfully display an OpenTok Recorder. (For more information, see Connection Token Creation.) The second parameter is the ID of the replacement HTML DOM element.

When the user starts recording, the Recorder object dispatches a recordingStarted event. The event listener for this event calls the getImgData() method of the Recorder object:

function recStartedHandler(event) {
    recImgData = recorder.getImgData();
}

The getImgData() method returns a base-64-encoded string of PNG data representing the Recorder video.

When the user saves the archive, the Recorder object dispatches a archiveSaved event. The event listener for this event adds the screen capture image to the page:

function archiveSavedHandler(event) {
    document.getElementById('archiveList').style.display = 'block';
    var aLink = document.createElement('a');
    aLink.setAttribute('href',
                       "javascript:loadArchiveInPlayer(\"' + event.archives[0].archiveId + '\")');
    var recImg = getImg(recImgData);
    recImg.setAttribute('style', 'width:80; height:60; margin-right:2px');
    aLink.appendChild(recImg);
    document.getElementById('archiveList').appendChild(aLink);
}

The show() function simply makes HTML elements visible:

function show(id) {
    document.getElementById(id).style.display = 'block';
}

The HTML generated by the archiveSavedHandler looks like this:

<a href="javascript:loadArchive('archiveID')"><img style="width: 80px; height: 60px; margin-right: 2px;" src="imageData"></a>

When the user clicks the link, it will cause the page to display an OpenTok Player for the archive (see the next section).

In your application, you may want to save the archive ID and the PNG image data on your server. You can then retrieve the data later when you want to play back the archive ID in a future session (or if you want to display a preview thumbnail image of the archive).

Playing back stand-alone archives in the Player

The loadArchiveInPlayer() method creates an OpenTok Player object by calling the displayPlayer() method of the RecorderManager object:

function loadArchiveInPlayer(archiveId) {
    if (!player) {
        playerDiv = document.createElement('div');
        playerDiv.setAttribute('id', 'playerElement');
        document.getElementById('playerContainer').appendChild(playerDiv)
        player = recorderManager.displayPlayer(archiveId, TOKEN, playerDiv.id);
        document.getElementById('playerContainer').style.display = 'block';
    else {
        player.loadArchive(archiveId);
    }
}

The first parameter of the displayPlayer() method is the archive ID of the stand-alone archive you wish to play back. The second parameter of the displayPlayer() method is an OpenTok token string. The token must include the "moderator" role to successfully display an OpenTok Player. You assign roles to tokens using the generate_token() method of the OpenTok server-side libraries or the Dashboard page. (For more information, see Connection Token Creation.) The third parameter is the ID of the replacement HTML DOM element.

If the Player object has already been created, the loadArchiveInPlayer() function calls the loadArchive() method of the Player object. This loads the selected archive in the Player.

Playing back stand-alone archives in an OpenTok session

You can also play back a stand-alone recording in an OpenTok session. The recording plays back in the session as a stream that clients can subscribe to. This lets all participants in a session view the recording play back simultaneously. However, this sample application does not include code for this — it only plays the recording in the stand-alone player.

Call the loadArchive() method of the Session object loads the archive in the session. When the archive is loaded, the Session object dispatches a archiveLoaded event. You can then call the startPlayback() method of the Archive object (which is the archives[0] property of the archiveLoaded event object):

session.addEventListener("archiveLoaded", archiveLoadedHandler);
session.loadArchive(archiveId);

function archiveLoadedHandler(event) {
    archive = event.archives[0];
    archive.startPlayback();
}

Note: The API key you used when creating the stand-alone recording (by calling TB.initRecorderManager() method) must match the API used when you create the OpenTok session (using the server-side API). Only a client that connects to a session with a token that has been assigned the role of moderator can load archives (using the Session.loadArchive() method).

The Session object dispatches a streamCreated event when the archive stream starts playing back. In the event handler for the streamCreated event, subscribe to the stream, just as you would subscribe to a live stream in the session. (You can differentiate between a live stream and a recoded stream by the type property of the Stream object. (The type property is set to "archive" for an archive playback stream.) For example, in the following code, the streamCreatedHandler() function is assumed to be the event listener for the streamCreated event. The addStream() function then subscribes to streams (and labels them as either "live" or "recorded").

function streamCreatedHandler(event) {
    // Subscribe to the newly created streams
    for (var i = 0; i < event.streams.length; i++) {
        addStream(event.streams[i]);
    }
}

function addStream(stream) {
    // Check if this is the stream that I am publishing, and if so do not subscribe.
    if (stream.connection.connectionId == session.connection.connectionId) {
        return;
    }

    // Create the container for the subscriber
    var container = document.createElement('div');
    var containerId = 'container_' + stream.streamId;
    container.setAttribute('id', containerId);
    container.className = 'swfContainer';

    // The following assumes that there is a DOM element named "subscribersContainer".
    var subscribersContainer = document.getElementById('subscribersContainer');
    subscribersContainer.appendChild(container);

    // Create the div that will be replaced by the subscriber
    var div = document.createElement('div');
    var divId = stream.streamId;
    div.setAttribute('id', divId);
    div.style.float = 'top';
    container.appendChild(div);

    // Label the stream as "Recorded" or "Live."
    var label = document.createElement('p');
    label.style.marginTop = '0px';
    switch (stream.type) {
        case 'archive' :
            label.innerHTML = 'Recorded';
            break;
        case 'basic' :
            label.innerHTML = 'Live';
            break;
    }
    container.appendChild(label);

    subscribers[stream.streamId] = session.subscribe(stream, divId);
}

 

More OpenTok archiving features

Stand-alone recordings are just one feature of the OpenTok archiving API. You can also record and play back OpenTok sessions. For more information, see the Archiving overview.

For more information on stand-alone archives, see Recording and playing back stand-alone archives. Also see the Recorder, RecorderManager, and Player classes in the OpenTok JavaScript API reference.

IRC Live Chat

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