thibauts / node-castv2-client

A Chromecast client based on the new (CASTV2) protocol
MIT License
646 stars 92 forks source link

.play() / .pause() causes error Cannot read property 'mediaSessionId' of null #81

Open untitledlt opened 6 years ago

untitledlt commented 6 years ago

Here's my code

client.getSessions(function(err, sessions) {
    const session = sessions[0];
        client.join(session, DefaultMediaReceiver, function(err, app) {
            app.pause();
         });
     });
});

And it causes this error:

/workplace/chromecast/node-castv2-client/node_modules/castv2-client/lib/controllers/media.js:88
  data.mediaSessionId = this.currentSession.mediaSessionId;
                                            ^
TypeError: Cannot read property 'mediaSessionId' of null
at fn.MediaController.sessionRequest (/workplace/chromecast/node-castv2-client/node_modules/castv2-client/lib/controllers/media.js:88:45)
at fn.MediaController.pause (/workplace/chromecast/node-castv2-client/node_modules/castv2-client/lib/controllers/media.js:103:8)
at DefaultMediaReceiver.pause (/workplace/chromecast/node-castv2-client/node_modules/castv2-client/lib/senders/default-media-receiver.js:38:20)
at /workplace/chromecast/node-castv2-client/app.js:39:21
at PlatformSender.join (/workplace/chromecast/node-castv2-client/node_modules/castv2-client/lib/senders/platform.js:88:3)
at /workplace/chromecast/node-castv2-client/app.js:30:20
at /workplace/chromecast/node-castv2-client/node_modules/castv2-client/lib/controllers/receiver.js:86:5
at /workplace/chromecast/node-castv2-client/node_modules/castv2-client/lib/controllers/receiver.js:31:5
at fn.onmessage (/workplace/chromecast/node-castv2-client/node_modules/castv2-client/lib/controllers/request-response.js:27:7)
at emitTwo (events.js:131:20)

I can read app status with app.on('status', () => {}) so i guess connection is fine. Tried while playing Spotify and Google Play Music.

Do I need to set currentSession myself or is it a bug? Any easy fixes for it?

pedromsilvapt commented 6 years ago

It seems that when joining an already existing app (instead of launching it) the current session isn't registered.

This happened to me once and I solved it by calling the app.getStatus() first. You can even check if the variable is undefined to avoid calling getStatus() unnecessarily. Try and see if this fixes it.

client.getSessions(function(err, sessions) {
    const session = sessions[0];
        client.join(session, DefaultMediaReceiver, function(err, app) {
            if (!app.media.currentSession){
                app.getStatus(function() {
                    app.pause();
                });
            } else {
                app.pause();
            }
         });
     });
});