Opentok在会话之间切换

时间:2014-12-15 12:28:24

标签: javascript opentok

我正在创建一个应用程序,用户可以在不同的语音室(会话)之间切换。 功能' connectToSession' (见下文)检查用户是否已经在会话中,如果是,将断开与当前会话的连接,然后连接到其他会话并将其流发布到该会话。

语音室的切换工作正常,并且用户可以正常工作,但每次用户切换会话时,我都会在控制台中收到此错误:

Publisher State Change Failed:  'Publishing' cannot transition to 'PublishingToSession'
Publisher State Change Failed:  'Publishing' cannot transition to 'Publishing'

从我的调试开始,它似乎发生在调用session.publish的行

var session = null;
var publisher = null;
var subscribers = {};

function connectToSession(sessionId, token) {
    if (session) {
        session.disconnect();
    }

    if (!publisher) {
        //First time so we need to initialise publisher
        var pubOptions = {
            videoSource: null,
            name: user_id
        };

        publisher = OT.initPublisher(null, pubOptions, function() {
            //Publisher initialised
        });

        publisher.on({
            'streamDestroyed': function(event) {
                event.preventDefault();
            }
        });
    }

    session = OT.initSession(apiKey, sessionId);

    session.on({
        'streamCreated': function(event) {
            // Subscribe to others stream
            subscribers[event.stream.name] = session.subscribe(event.stream);
        },
        'sessionConnected': function(sessionConnectEvent) {
            // Session Connected
        },
        'streamDestroyed': function(event) {
            //Stream removed from session
            delete subscribers[event.stream.name];
        }
    });

    session.connect(token,
        function(error) {
            if (error) {
                console.error(error);
            }
            else {
                session.publish(publisher, function() {
                        //Finished publishing
                    }
                );
            }
    });
}

任何想法导致此错误的原因是什么?

1 个答案:

答案 0 :(得分:1)

if (session) {
    if (publisher) {
        session.unpublish(publisher);
    }
    session.disconnect();
}

解决方法是在断开与会话的连接之前为发布者显式调用取消发布。