8

I looked at these links

http://www.tokbox.com/opentok/api/tools/js/documentation/overview/publish.html

http://www.tokbox.com/opentok/api/tools/js/tutorials/overview

but their are no examples for publishingunpublishing manually, that is, publishing/unpublishing without using 'streamCreated'/'streamDestroyed' event handler respectively.

The reason I want to do this is that I have a button to publish/unpublish so that the user can do it at will.

Is there a way to do this?

developarvin
  • 4,594
  • 12
  • 48
  • 97

1 Answers1

4

Yes and it is very simple. Check out the prepublish source code to see how. There are 2 functions, startPublishing() and stopPublishing() which achieve this.

Primarily they use session.publish(publisher);to publish and session.unpublish(publisher); to unpublish.

Here is code I have used to work off:

// Called by a button to start publishing to the session
function startPublishing() {
    if (!publisher) {
        var parentDiv = document.getElementById("myCamera");
        var publisherDiv = document.createElement('div'); // Create a div for the publisher to replace
        publisherDiv.setAttribute('id', 'opentok_publisher');
        parentDiv.appendChild(publisherDiv);
        var publisherProps = {
            width : VIDEO_WIDTH,
            height : VIDEO_HEIGHT
        };
        publisher = TB.initPublisher(apiKey, publisherDiv.id, publisherProps); // Pass the replacement div id and properties
        session.publish(publisher);
        show('unpublishLink');
        hide('publishLink');
    }
}

//Called by a button to stop publishing to the session
function stopPublishing() {
    if (publisher) {
        session.unpublish(publisher);
    }
    publisher = null;

    show('publishLink');
    hide('unpublishLink');
}
Rick Donohoe
  • 6,141
  • 6
  • 24
  • 38
  • 3
    My code uses the .publish() and .unpublish() methods too. The problem is that when I publish after unpublishing, it doesn't show anything. – developarvin Oct 22 '12 at 09:58
  • 3
    I also tried the live demo on the link you gave. Tried to unpublish and then republish. Didn't work. – developarvin Oct 22 '12 at 10:21
  • 3
    Don't forget when you unpublish it destroys the div which it replaced, so you need to make sure it can attach itself to something again. I had a similar problem! – Rick Donohoe Oct 22 '12 at 10:21
  • Also I didn't realize the tutorial didn't do this already so +1 on the Q. – Rick Donohoe Oct 22 '12 at 12:05