I'm trying to have clients publish a A/V stream, turn them off, and then turn them back on. The first time I tell them to publish and then unpublish, it works fine. However, the next time I tell them to publish (Using the same session ID and token), I get the error "Cannot Connect, the session is already undefined".
Why is the "session" getting destroyed?.. is it the unpublish? My code is pretty much taken from the tutorials:
clientSession = OT.initSession(apiKey, sessionId);
clientSession.connect(token, function (error) {
if (error) {
handleError(error);
} else {
clientPublisher = OT.initPublisher(container, {
insertMode: 'append',
width: '100%',
height: '100%'
}, handleError);
}
});
}
To unpublish:
clientSession.unpublish(clientPublisher);
There are 2 ways you could do this. You could initialise a single publisher object once and keep reusing it everytime you republish. Or you could keep destroying and reinitialising a new publisher each time. I've written up an example of both approaches for you:
Note: Please provide your own API key, session ID and token to run the above JSbins
The key difference is that to reuse a publisher you need to do this:
pub.on('streamDestroyed', e => e.preventDefault());
This is documented here: https://tokbox.com/developer/sdks/js/reference/Publisher.html#.event:streamDestroyed
It makes sure that when you unpublish, the publisher object is not destroyed so it can be reused.
What also happens is if you reuse a publisher, the publisher remains on the page and the user can still see themselves. Even if the publisher is not streaming to the session. You could use CSS or DOM manipulation to hide the publisher, but the webcam light will remain on.
However, if you destroy and recreate the publisher each time, the publisher disappears from the page and the webcam light turns off while unpublished. Depending on the browser and the user's settings, they may be asked to permit access to their webcam again.