Getting Started with the OpenTok Archiving API

    Get started recording and playing back OpenTok archives in less than 15 minutes. Follow the steps below:

  1. 1Create an OpenTok archive
  2. 2Publish and record
  3. 3Stop recording and close archive
  4. 4Load and play back archive
  5. This tutorial is meant for those who learn by doing. You will build a simple application that records and plays back an OpenTok session.

    Before reading this tutorial, you should be familiar with the basics of using the OpenTok API. You should know how to use the OpenTok JavaScript library to connect to sessions, publish videos, and subscribe to videos. You can learn more about this at the basic API Getting Started page.

    You can also download the source code for a simple archiving demo. To use this demo, modify the source code to include valid API key and session ID values. Then open the page in a browser and click links in the page (such as Create Archive, Publish, Record Session, Stop Recording, Close Archive, Load Archive, and Start Playback).

    Note: The OpenTok archiving API also includes a stand-alone archive feature. This lets you record a video outside of an OpenTok session. For more information, see Recording stand-alone archives.

  1. 1Create an OpenTok archive

    When this page loads, it initializes and connects to a new OpenTok session. In your own page, you will use your own OpenTok API key and an OpenTok session that you generate. The page connects with the 'moderator_token' test token. Only users that connect using a token that has a role of moderator can create, load, record to, and play back archives.

    Upon connecting to the session, the page enables the Execute code button below. When you click the Execute code button, the code connects to the OpenTok session. When connected to the session, the code creates an OpenTok archive by calling the createArchive() method of the Session object (line 13). The first parameter of the createArchive() method is your API key. The second parameter defines the type of archive to be created. There are three types of archive: per-session, per-stream, and individual archives. The getting started code uses a per-session archive, which records all active streams in a session. You can use a per-stream archive to specify streams recorded in a session.

    When the archive is created, the Session object dispatches an archiveCreated event. The ArchiveEvent class defines this event. The archives[0] property of the event is a reference to the created archive (see lines 17 and 18). Note that this application maintains a record to the archive ID in JavaScript, in the archiveId variable. You may want to store archive IDs in a server-side database so that the archives can be loaded in other sessions and in other clients.

    Execute the code to connect to the session and create the archive. You will receive an alert when the archive is created.

     
                var apiKey = '1127';
                var sessionId = '14685d1ac5907f4a2814fed28294d3f797f34955';
                var token = 'moderator_token';	
                var archive;
                var archiveId;					
    
                var session = TB.initSession(sessionId);			
                session.addEventListener('sessionConnected', sessionConnectedHandler);			
                session.connect(apiKey, token);
    
                function sessionConnectedHandler(event) {
                    session.addEventListener('archiveCreated', archiveCreatedHandler);
                    session.createArchive(apiKey, 'perSession');
                }
                
                function archiveCreatedHandler(event) {
                    archive = event.archives[0];
                    archiveId = archive.archiveId;
                    alert("Archive created.");
                }
  2. 2Publish and record

    Once we've created the archive, call session.startRecording() to start recording the session (line 3).The Session object dispatches a sessionRecordingStarted event when the recording starts (line 2). At this point, we create a new Publisher object and publish a video. Click OK in the notification to allow camera and microphone access to to the page (if it is displayed). Be sure to wait at least 10 seconds before proceeding to the next step.

    This sample code only publishes one audio-video stream to a session. However, if other streams were published, they would be recorded to the archive, too.

    Execute the code to start recording and publish your stream.

                function startButtonClickHandler() {
                    session.addEventListener('sessionRecordingStarted', sessionRecordingStartedHandler);
                    session.startRecording(archive);
                }
    
                var publisher;
    
                function sessionRecordingStartedHandler(event) {
                    // Publish my webcam stream and put it in a div
                    publisher = session.publish('myPublisherDiv');
                }

    Note: In this sample, the publisher is added in response to the sessionRecordingStarted event. The order in which your app (a) publishes videos (or lets clients start publishing) and (b) starts recording a session is up to your own requirements. For example, you may have a multi-stream session that a moderator starts recording at an arbitrary time after the session starts.

  3. 3Stop recording and close archive

    To stop recording the archive, call the stopRecording() method of the Session object (line 3). When the recording stops, the Session object dispatches a sessionRecordingStopped event (line 2). In the event handler for this event, call the closeArchive() method of the Session object (line 8). Closing the archive makes it available to load and play back.

    Execute the code to stop recording and close the archive. (The code also stops publishing to the session.)

                function stopButtonClickHandler() {
                    session.addEventListener('sessionRecordingStopped', sessionRecordingStoppedHandler);
                    session.stopRecording(archive);
                }
    
                function sessionRecordingStoppedHandler(event) {
                    session.addEventListener("archiveClosed", archiveClosedHandler);
                    session.closeArchive(archive);
                    session.unpublish(publisher);
                }
                function archiveClosedHandler(event) {
                     alert("Recording stopped.");
                }
  4. 4Load and play back archive

    Before you can play back an archive, you must load it. Call the loadArchive() method of the Session object (line 2). Once the archive is loaded, the Session object dispatches a archiveLoaded event (line 1).

    Once the archive is loaded, you can play it back. Call the startPlayback() method of the Archive object (line 8). The archives[0] property of the archiveLoaded event object is the loaded archive (line 7).

    When the archive has stopped playing back, the Session object dispatches a playbackStopped event (line 5).

                session.addEventListener('archiveLoaded', archiveLoadedHandler);
                session.loadArchive(archiveId);
                
                function archiveLoadedHandler(event) {
                    session.addEventListener('playbackStopped', playbackStoppedHandler);
                    session.addEventListener('streamCreated', streamCreatedHandler);
                    archive = event.archives[0];
                    archive.startPlayback();
                    var playBtn = document.getElementById("playStopBtn");
                    playBtn.setAttribute('disabled', 'disabled');
                }
                
                function playbackStoppedHandler(event) {
                    var playBtn = document.getElementById("playStopBtn");
                    playBtn.setAttribute('disabled', '');
                }		
                
                function streamCreatedHandler(event) {
                    subscribeToStreams(event.streams);
                }
                
                function subscribeToStreams(streams) {
                    for (var i = 0; i < streams.length; i++) {
                        if (streams[i].type == "archive") {
                            var div = document.createElement('div');
                            div.setAttribute('id', 'stream' + streams[i].streamId);
                            document.getElementById('subscriberStreamContainer').appendChild(div);
    
                            session.subscribe(streams[i], div.id);
                        }
                    }
                }

Next Steps

Congrats! You've now learned how to record an OpenTok session to an archive and play it back (hopefully in less than 15 minutes).

If you'd like to learn more, we suggest that you read the main archiving page and the workflow overview.

Launch Your App

When you're done building your app, fill out the launch form to get access to our production servers for improved performance. Learn how to move your application from the staging servers (used in this tutorial) to production here.

IRC Live Chat

Have a quick question? Chat with other developers.  Join chat

TokBox staff may not be online right now. To reach them during off-hours, visit the forums.