OpenTok - How to publish/unpublish manually?
Asked Answered
U

1

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?

Ursala answered 22/10, 2012 at 9:7 Comment(0)
V
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');
}
Vitek answered 22/10, 2012 at 9:38 Comment(4)
My code uses the .publish() and .unpublish() methods too. The problem is that when I publish after unpublishing, it doesn't show anything.Ursala
I also tried the live demo on the link you gave. Tried to unpublish and then republish. Didn't work.Ursala
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!Vitek
Also I didn't realize the tutorial didn't do this already so +1 on the Q.Vitek

© 2022 - 2024 — McMap. All rights reserved.