### Install castv2-client Source: https://github.com/thibauts/node-castv2-client/blob/master/README.md Install the castv2-client package using npm. For Windows, use the --no-optional flag to avoid native module dependencies. ```bash npm install castv2-client ``` ```bash npm install castv2-client --no-optional ``` -------------------------------- ### Set up CORS for subtitle and video tracks Source: https://github.com/thibauts/node-castv2-client/wiki/How-to-use-subtitles-with-the-DefaultMediaReceiver-app Ensure your subtitle and video tracks are hosted on a server supporting CORS. This example shows a basic express server setup for CORS. ```javascript app.use(function(req, res, next) { if(req.headers.origin) { res.headers['Access-Control-Allow-Origin'] = req.headers.origin; } next(); }); app.use(express.static(__dirname)); ``` -------------------------------- ### Launch Stream on Chromecast Source: https://github.com/thibauts/node-castv2-client/blob/master/README.md Connect to a Chromecast device and launch a media stream using the DefaultMediaReceiver. This example demonstrates discovering devices, connecting, launching the app, loading media, and handling player status updates and seeking. ```javascript var Client = require('castv2-client').Client; var DefaultMediaReceiver = require('castv2-client').DefaultMediaReceiver; var mdns = require('mdns'); var browser = mdns.createBrowser(mdns.tcp('googlecast')); browser.on('serviceUp', function(service) { console.log('found device "%s" at %s:%d', service.name, service.addresses[0], service.port); ondeviceup(service.addresses[0]); browser.stop(); }); browser.start(); function ondeviceup(host) { var client = new Client(); client.connect(host, function() { console.log('connected, launching app ...'); client.launch(DefaultMediaReceiver, function(err, player) { var media = { // Here you can plug an URL to any mp4, webm, mp3 or jpg file with the proper contentType. contentId: 'http://commondatastorage.googleapis.com/gtv-videos-bucket/big_buck_bunny_1080p.mp4', contentType: 'video/mp4', streamType: 'BUFFERED', // or LIVE // Title and cover displayed while buffering metadata: { type: 0, metadataType: 0, title: "Big Buck Bunny", images: [ { url: 'http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/images/BigBuckBunny.jpg' } ] } }; player.on('status', function(status) { console.log('status broadcast playerState=%s', status.playerState); }); console.log('app "%s" launched, loading media %s ...', player.session.displayName, media.contentId); player.load(media, { autoplay: true }, function(err, status) { console.log('media loaded playerState=%s', status.playerState); // Seek to 2 minutes after 15 seconds playing. setTimeout(function() { player.seek(2*60, function(err, status) { // }); }, 15000); }); }); }); client.on('error', function(err) { console.log('Error: %s', err.message); client.close(); }); } ``` -------------------------------- ### MediaController Source: https://context7.com/thibauts/node-castv2-client/llms.txt Handles the media namespace for controlling media playback. Provides methods for loading, playing, pausing, stopping, seeking, and getting media status. Emits broadcast status events for player state changes. ```APIDOC ## MediaController ### Description Handles the `urn:x-cast:com.google.cast.media` namespace. Tracks `currentSession` (last known media session). Provides `load`, `play`, `pause`, `stop`, `seek`, `getStatus`, and all `queue*` methods. Emits broadcast `status` events whenever the player state changes. ### Usage ```javascript var MediaController = require('castv2-client').MediaController; var media = sender.createController(MediaController); media.on('status', function(status) { console.log('Media status broadcast:', status.playerState, '@', status.currentTime); }); media.load( { contentId: 'http://example.com/video.mp4', contentType: 'video/mp4', streamType: 'BUFFERED' }, { autoplay: true }, function(err, status) { if (err) return console.error(err); console.log('Loaded. SessionId:', status.mediaSessionId); } ); ``` ``` -------------------------------- ### Get current media status using player.getStatus() Source: https://context7.com/thibauts/node-castv2-client/llms.txt Requests the current media session status from the device. Useful for retrieving playerState, currentTime, duration, and media metadata. ```javascript player.getStatus(function(err, status) { if (err) return console.error(err); console.log('State:', status.playerState); // e.g. 'PLAYING' console.log('Time:', status.currentTime); // e.g. 42.3 (seconds) console.log('Duration:', status.media.duration); }); ``` -------------------------------- ### HeartbeatController Source: https://context7.com/thibauts/node-castv2-client/llms.txt Manages periodic PING/PONG keep-alive messages. Call start() to begin and stop() to end. Emits a 'timeout' event if no PONG is received within the expected timeframe. ```APIDOC ## HeartbeatController ### Description Manages periodic PING/PONG keep-alive messages on `urn:x-cast:com.google.cast.tp.heartbeat`. Call `start(intervalSeconds)` to begin (default 5 s). Emits `timeout` if no PONG is received within `interval × 3` seconds. ### Usage ```javascript var HeartbeatController = require('castv2-client').HeartbeatController; var hb = sender.createController(HeartbeatController); hb.once('timeout', function() { console.error('Device heartbeat timed out'); }); hb.start(5); // ping every 5 seconds // later, before closing: hb.stop(); ``` ``` -------------------------------- ### Get Device Volume with client.getVolume Source: https://context7.com/thibauts/node-castv2-client/llms.txt Retrieves the current volume level and mute state of the Chromecast device. The callback receives an object containing `level` and `muted` properties. ```javascript client.connect('192.168.1.42', function() { client.getVolume(function(err, volume) { if (err) return console.error(err); console.log('Level:', volume.level); // e.g. 0.5 console.log('Muted:', volume.muted); // e.g. false client.close(); }); }); ``` -------------------------------- ### Heartbeat Controller Management Source: https://context7.com/thibauts/node-castv2-client/llms.txt Manage keep-alive messages with `HeartbeatController`. Start periodic PING/PONG messages and listen for `timeout` events if a PONG is not received within the expected timeframe. ```javascript var HeartbeatController = require('castv2-client').HeartbeatController; var hb = sender.createController(HeartbeatController); hb.once('timeout', function() { console.error('Device heartbeat timed out'); }); hb.start(5); // ping every 5 seconds // later, before closing: hb.stop(); ``` -------------------------------- ### Multicast DNS Scanner for Chromecast Devices Source: https://github.com/thibauts/node-castv2-client/wiki/How-to-discover-&-update-audio-groups This JavaScript function scans for Chromecast devices on the local network using multicast DNS. It requires callbacks for new devices and updates, and allows configuration of the scan interval. Ensure the 'multicast-dns', 'array-find', 'xtend', and 'mdns-txt' modules are installed. ```javascript var util = require('util'); var mdns = require('multicast-dns'); var find = require('array-find'); var xtend = require('xtend'); var txt = require('mdns-txt')(); function mdsn_scan(cb_new, scan_interval, cb_update){ var m = mdns(); var found_devices = {}; var onResponse = function(response) { var txt_field = find(response.additionals, function(entry) { return entry.type === 'TXT'; }); var srv_field = find(response.additionals, function(entry) { return entry.type === 'SRV'; }); var a_field = find(response.additionals, function(entry) { return entry.type === 'A'; }); if (!txt_field || !srv_field || !a_field) { return; } //console.log('txt:\n', util.inspect(txt.decode(txt_field.data))); var ip = a_field.data; var name = txt.decode(txt_field.data).fn; var port = srv_field.data.port; if (!ip || !name || !port) { return; } if (name in found_devices) { //We have seen this device already old_device = found_devices[name]; if (old_device.ip != ip || old_device.port != port) { //device has changed old_device.ip = ip; old_device.port = port; if (cb_update) cb_update(name, ip, port); } } else { //First time we see this device found_devices[name]={ ip: ip, port: port }; if (cb_new) cb_new(name, ip, port); } } m.on('response', onResponse); function sendQuery(){ //console.log("Sending query"); m.query({ questions:[{ name: '_googlecast._tcp.local', type: 'PTR' }] }); } sendQuery(); if (scan_interval) setInterval(sendQuery, scan_interval); } ``` -------------------------------- ### client.connect Source: https://context7.com/thibauts/node-castv2-client/llms.txt Establishes a connection to a Chromecast device and sets up necessary controllers. ```APIDOC ## client.connect(options, callback) ### Description Establishes a TLS connection to the Chromecast device. It automatically sets up connection, heartbeat, and receiver sub-controllers. The `options` can be a hostname string or an object `{ host, port }`. The `callback` is invoked when the connection is ready. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Method Connect ### Endpoint N/A (Method call) ### Request Example ```javascript var client = new Client(); // Connect using a host string (default port 8009) client.connect('192.168.1.42', function() { console.log('Connected'); }); // Connect using an options object with explicit port client.connect({ host: '192.168.1.42', port: 8009 }, function() { console.log('Connected with explicit port'); }); client.on('error', function(err) { console.error('Connection error:', err.message); client.close(); }); ``` ### Response #### Success Response (Callback) - `callback()`: Called upon successful connection. #### Response Example N/A ``` -------------------------------- ### ReceiverController Source: https://context7.com/thibauts/node-castv2-client/llms.txt Handles the receiver namespace for controlling the Chromecast receiver. Provides methods for getting status, app availability, launching/stopping apps, and managing volume. ```APIDOC ## ReceiverController ### Description Handles the `urn:x-cast:com.google.cast.receiver` namespace. Provides methods for `getStatus`, `getAppAvailability`, `launch`, `stop`, `setVolume`, `getVolume`, and `getSessions`. Emits broadcast `status` events for receiver status changes. ### Usage ```javascript var ReceiverController = require('castv2-client').ReceiverController; var receiver = sender.createController(ReceiverController); receiver.on('status', function(status) { console.log('Broadcast receiver status:', status); }); receiver.getStatus(function(err, status) { console.log('Volume level:', status.volume.level); console.log('Running apps:', status.applications); }); receiver.launch('CC1AD845', function(err, sessions) { if (err) return console.error('Launch failed:', err.message); console.log('Launched session:', sessions[0].sessionId); }); ``` ``` -------------------------------- ### client.launch(Application, callback) Source: https://context7.com/thibauts/node-castv2-client/llms.txt Launches the specified Application class on the Chromecast device. The Application must expose a static `APP_ID` string. Calls `callback(err, appInstance)` with the running application sender object on success. ```APIDOC ## client.launch(Application, callback) ### Description Launches the specified Application class on the Chromecast device. The Application must expose a static `APP_ID` string. Calls `callback(err, appInstance)` with the running application sender object on success. ### Parameters #### Path Parameters - **Application** (class) - Required - The Application class to launch (e.g., DefaultMediaReceiver). #### Callback Parameters - **err** (Error) - An error object if the operation failed. - **appInstance** (object) - The sender object for the running application. ``` -------------------------------- ### Get Chromecast Receiver Status Source: https://context7.com/thibauts/node-castv2-client/llms.txt Query the Chromecast receiver for its current status, including running applications and volume level. The status object is passed to the callback. ```javascript client.connect('192.168.1.42', function() { client.getStatus(function(err, status) { if (err) return console.error(err); // status.applications — array of running apps // status.volume — { level: 0.5, muted: false } console.log('Running apps:', status.applications); console.log('Volume:', status.volume); client.close(); }); }); ``` -------------------------------- ### Client Constructor Source: https://context7.com/thibauts/node-castv2-client/llms.txt Creates a new instance of the Chromecast client. This is the primary entry point for interacting with the library. ```APIDOC ## new Client() ### Description Creates a Chromecast client instance. This class extends `Sender` and `EventEmitter`, managing internal controllers for connection, heartbeat, and receiver status once connected. It emits 'status' for receiver broadcasts and 'error' for connection issues. ### Usage ```javascript var Client = require('castv2-client').Client; var client = new Client(); ``` ``` -------------------------------- ### player.queueLoad Source: https://context7.com/thibauts/node-castv2-client/llms.txt Loads an ordered list of media items as a queue. Each item in `items` is an object with `media`, `autoplay`, `preloadTime`, `startTime`, `playbackDuration`, and `activeTrackIds`. Options: `startIndex`, `repeatMode` (`'REPEAT_OFF'`, `'REPEAT_ALL'`, `'REPEAT_SINGLE'`, `'REPEAT_ALL_AND_SHUFFLE'`). ```APIDOC ## player.queueLoad(items, options, callback) — Load a media queue (playlist) ### Description Loads an ordered list of media items as a queue. ### Parameters #### items - **media** (object) - Required - Media item details. - **autoplay** (boolean) - Optional - Whether to autoplay. - **preloadTime** (number) - Optional - Time in seconds to preload. - **startTime** (number) - Optional - Start time in seconds. - **playbackDuration** (number) - Optional - Duration of playback in seconds. - **activeTrackIds** (array) - Optional - IDs of active tracks. #### options - **startIndex** (number) - Optional - The index to start playback from. - **repeatMode** (string) - Optional - The repeat mode for the queue. Possible values: `'REPEAT_OFF'`, `'REPEAT_ALL'`, `'REPEAT_SINGLE'`, `'REPEAT_ALL_AND_SHUFFLE'`. #### callback - **err** - Error object if an error occurred. - **status** - Status object of the player. ### Request Example ```javascript var playlist = [ { autoplay: true, preloadTime: 3, startTime: 0, activeTrackIds: [], media: { contentId: 'http://example.com/track1.mp3', contentType: 'audio/mpeg', streamType: 'BUFFERED' } }, { autoplay: true, preloadTime: 3, startTime: 0, activeTrackIds: [], media: { contentId: 'http://example.com/track2.mp3', contentType: 'audio/mpeg', streamType: 'BUFFERED' } } ]; player.queueLoad(playlist, { startIndex: 0, repeatMode: 'REPEAT_ALL' }, function(err, status) { if (err) return console.error('Queue load error:', err.message); console.log('Queue loaded. State:', status.playerState); }); ``` ``` -------------------------------- ### Connect to Chromecast with Options Source: https://context7.com/thibauts/node-castv2-client/llms.txt Connect to a Chromecast device using either a host string or an options object specifying host and port. Includes error handling. ```javascript var client = new Client(); // Connect using a host string (default port 8009) client.connect('192.168.1.42', function() { console.log('Connected'); }); // Connect using an options object with explicit port client.connect({ host: '192.168.1.42', port: 8009 }, function() { console.log('Connected with explicit port'); }); client.on('error', function(err) { console.error('Connection error:', err.message); client.close(); }); ``` -------------------------------- ### Instantiate and Connect Chromecast Client Source: https://context7.com/thibauts/node-castv2-client/llms.txt Instantiate the Client and connect to a Chromecast device by IP address. Listen for status updates and errors. Requires importing Client and DefaultMediaReceiver. ```javascript var Client = require('castv2-client').Client; var DefaultMediaReceiver = require('castv2-client').DefaultMediaReceiver; var client = new Client(); // Connect to a Chromecast device by IP (optionally pass a port, default 8009) client.connect('192.168.1.42', function() { console.log('Connected to Chromecast'); // Listen for receiver status broadcasts (volume changes, app launches, etc.) client.on('status', function(status) { console.log('Receiver status:', status); }); // Handle errors client.on('error', function(err) { console.error('Client error:', err.message); client.close(); }); }); ``` -------------------------------- ### Receiver Controller Operations Source: https://context7.com/thibauts/node-castv2-client/llms.txt Control the Chromecast receiver using `ReceiverController`. Get status, manage app availability, launch/stop applications, and control volume. It also emits `status` events for receiver state changes. ```javascript var ReceiverController = require('castv2-client').ReceiverController; var receiver = sender.createController(ReceiverController); receiver.on('status', function(status) { console.log('Broadcast receiver status:', status); }); receiver.getStatus(function(err, status) { console.log('Volume level:', status.volume.level); console.log('Running apps:', status.applications); }); receiver.launch('CC1AD845', function(err, sessions) { if (err) return console.error('Launch failed:', err.message); console.log('Launched session:', sessions[0].sessionId); }); ``` -------------------------------- ### client.join(session, Application, callback) Source: https://context7.com/thibauts/node-castv2-client/llms.txt Joins an already-running application session without relaunching it. Useful for re-attaching to a session after a disconnect or connecting from a second client. ```APIDOC ## client.join(session, Application, callback) ### Description Joins an already-running application session without relaunching it. Useful for re-attaching to a session after a disconnect or connecting from a second client. ### Parameters #### Path Parameters - **session** (object) - Required - The session object to join. - **Application** (class) - Required - The Application class associated with the session. #### Callback Parameters - **err** (Error) - An error object if the operation failed. - **appInstance** (object) - The sender object for the joined application. ``` -------------------------------- ### Create Custom Sender Application with Application Class Source: https://context7.com/thibauts/node-castv2-client/llms.txt Extends the base Application class to create a custom sender application. Automatically sets up a ConnectionController and allows adding protocol channels via createController. ```javascript var util = require('util'); var Application = require('castv2-client').Application; var RequestResponseController = require('castv2-client').RequestResponseController; function MyCustomApp(client, session) { Application.apply(this, arguments); // Add a custom protocol controller this.myController = this.createController( RequestResponseController, 'urn:x-cast:com.example.myapp' ); } MyCustomApp.APP_ID = 'MYAPP001'; util.inherits(MyCustomApp, Application); MyCustomApp.prototype.sendCommand = function(data, callback) { this.myController.request(data, callback); }; // Launch custom app client.launch(MyCustomApp, function(err, app) { if (err) return console.error(err); app.sendCommand({ type: 'HELLO' }, function(err, response) { console.log('Response:', response); }); }); ``` -------------------------------- ### Load Media Queue with player.queueLoad Source: https://context7.com/thibauts/node-castv2-client/llms.txt Loads an ordered list of media items as a queue. Each item requires media details, autoplay, preloadTime, startTime, activeTrackIds. Options include startIndex and repeatMode. ```javascript var playlist = [ { autoplay: true, preloadTime: 3, startTime: 0, activeTrackIds: [], media: { contentId: 'http://example.com/track1.mp3', contentType: 'audio/mpeg', streamType: 'BUFFERED' } }, { autoplay: true, preloadTime: 3, startTime: 0, activeTrackIds: [], media: { contentId: 'http://example.com/track2.mp3', contentType: 'audio/mpeg', streamType: 'BUFFERED' } } ]; player.queueLoad(playlist, { startIndex: 0, repeatMode: 'REPEAT_ALL' }, function(err, status) { if (err) return console.error('Queue load error:', err.message); console.log('Queue loaded. State:', status.playerState); }); ``` -------------------------------- ### Join Existing Session with client.join Source: https://context7.com/thibauts/node-castv2-client/llms.txt Joins an already running application session without relaunching it. This is useful for re-attaching to a session after a disconnection. The callback provides an `player` object for interacting with the session. ```javascript client.connect('192.168.1.42', function() { client.getSessions(function(err, sessions) { if (err || sessions.length === 0) return; var session = sessions[0]; client.join(session, DefaultMediaReceiver, function(err, player) { if (err) return console.error(err); console.log('Joined session:', session.sessionId); player.getStatus(function(err, status) { console.log('Current player state:', status.playerState); }); }); }); }); ``` -------------------------------- ### Custom Controller Implementation Source: https://context7.com/thibauts/node-castv2-client/llms.txt Extend the base `Controller` to create custom protocol channels. Implement message handling and define custom methods for sending data. ```javascript var Controller = require('castv2-client').Controller; var util = require('util'); function MyController(client, sourceId, destinationId) { Controller.call(this, client, sourceId, destinationId, 'urn:x-cast:com.example.protocol', 'JSON'); this.on('message', function(data, broadcast) { console.log('Received:', data, '| Broadcast:', broadcast); }); } util.inherits(MyController, Controller); MyController.prototype.sendHello = function() { this.send({ type: 'HELLO', message: 'world' }); }; ``` -------------------------------- ### Launch Application with client.launch Source: https://context7.com/thibauts/node-castv2-client/llms.txt Launches a specified application on the Chromecast device. The application must have a static `APP_ID`. The callback provides an `appInstance` object for controlling the running application. ```javascript var DefaultMediaReceiver = require('castv2-client').DefaultMediaReceiver; client.connect('192.168.1.42', function() { client.launch(DefaultMediaReceiver, function(err, player) { if (err) return console.error('Launch failed:', err.message); console.log('Launched app:', player.session.displayName); // player is a DefaultMediaReceiver instance ready for media commands }); }); ``` -------------------------------- ### client.getVolume(callback) Source: https://context7.com/thibauts/node-castv2-client/llms.txt Retrieves the current volume and mute state of the device. ```APIDOC ## client.getVolume(callback) ### Description Retrieves the current volume and mute state of the device. ### Parameters #### Callback Parameters - **err** (Error) - An error object if the operation failed. - **volume** (object) - An object containing the current volume and mute state. - **level** (number) - The current volume level (0.0 to 1.0). - **muted** (boolean) - The current mute state (true or false). ``` -------------------------------- ### client.stop(application, callback) Source: https://context7.com/thibauts/node-castv2-client/llms.txt Closes the given application instance and sends a STOP command to the receiver, terminating the session. ```APIDOC ## client.stop(application, callback) ### Description Closes the given application instance and sends a STOP command to the receiver, terminating the session. ### Parameters #### Path Parameters - **application** (object) - Required - The application instance to stop. #### Callback Parameters - **err** (Error) - An error object if the operation failed. - **sessions** (array) - An array of remaining sessions. ``` -------------------------------- ### Application Source: https://context7.com/thibauts/node-castv2-client/llms.txt Base class for custom sender applications. Extends `Sender` and `EventEmitter`. Used to create custom protocol controllers. ```APIDOC ## Application — Base class for custom sender applications ### Description Base class for custom sender applications. It takes a `client` and a `session` object and automatically sets up a `ConnectionController` on the session's `transportId`. Subclass it and call `this.createController(SomeController)` to add protocol channels. Emits `close` when the session ends. ### Methods #### createController(ControllerType, namespace) - Creates and registers a new protocol controller. #### sendCommand(data, callback) - Sends a command to the custom application. ### Example ```javascript var util = require('util'); var Application = require('castv2-client').Application; var RequestResponseController = require('castv2-client').RequestResponseController; function MyCustomApp(client, session) { Application.apply(this, arguments); // Add a custom protocol controller this.myController = this.createController( RequestResponseController, 'urn:x-cast:com.example.myapp' ); } MyCustomApp.APP_ID = 'MYAPP001'; util.inherits(MyCustomApp, Application); MyCustomApp.prototype.sendCommand = function(data, callback) { this.myController.request(data, callback); }; // Launch custom app client.launch(MyCustomApp, function(err, app) { if (err) return console.error(err); app.sendCommand({ type: 'HELLO' }, function(err, response) { console.log('Response:', response); }); }); ``` ``` -------------------------------- ### client.setVolume(options, callback) Source: https://context7.com/thibauts/node-castv2-client/llms.txt Sets the device volume level or mute state. Pass `{ level: 0.0–1.0 }` to change volume or `{ muted: true/false }` to toggle mute. Returns the updated volume object. ```APIDOC ## client.setVolume(options, callback) ### Description Sets the device volume level or mute state. Pass `{ level: 0.0–1.0 }` to change volume or `{ muted: true/false }` to toggle mute. Returns the updated volume object. ### Parameters #### Path Parameters - **options** (object) - Required - An object containing volume settings. - **level** (number) - Optional - The desired volume level (0.0 to 1.0). - **muted** (boolean) - Optional - The desired mute state (true or false). #### Callback Parameters - **err** (Error) - An error object if the operation failed. - **volume** (object) - The updated volume object, containing `level` and `muted` properties. ``` -------------------------------- ### Stop Application with client.stop Source: https://context7.com/thibauts/node-castv2-client/llms.txt Stops a running application instance and terminates the session by sending a STOP command to the receiver. The callback receives the remaining sessions. ```javascript client.connect('192.168.1.42', function() { client.launch(DefaultMediaReceiver, function(err, player) { if (err) return console.error(err); // Stop the app after 10 seconds setTimeout(function() { client.stop(player, function(err, sessions) { if (err) return console.error(err); console.log('App stopped. Remaining sessions:', sessions.length); client.close(); }); }, 10000); }); }); ``` -------------------------------- ### player.getStatus Source: https://context7.com/thibauts/node-castv2-client/llms.txt Requests the current media session status from the device. ```APIDOC ## player.getStatus(callback) ### Description Requests the current media session status from the device, including `playerState`, `currentTime`, `duration`, and media metadata. ### Parameters #### Callback - **callback** (function) - Called with the current status or an error. - **err** - Error object if the status request failed. - **status** (object) - The current status of the media player. - **playerState** (string) - The current state of the player (e.g., 'PLAYING'). - **currentTime** (number) - The current playback time in seconds. - **media** (object) - Information about the currently loaded media. - **duration** (number) - The total duration of the media in seconds. ### Example ```javascript player.getStatus(function(err, status) { if (err) return console.error(err); console.log('State:', status.playerState); // e.g. 'PLAYING' console.log('Time:', status.currentTime); // e.g. 42.3 (seconds) console.log('Duration:', status.media.duration); }); ``` ``` -------------------------------- ### client.getAppAvailability(appId, callback) Source: https://context7.com/thibauts/node-castv2-client/llms.txt Checks whether one or more application IDs are available on the device. `appId` can be a string or an array of strings. The callback receives an object mapping each app ID to a boolean. ```APIDOC ## client.getAppAvailability(appId, callback) ### Description Checks whether one or more application IDs are available on the device. `appId` can be a string or an array of strings. The callback receives an object mapping each app ID to a boolean. ### Parameters #### Path Parameters - **appId** (string | string[]) - Required - The application ID or an array of application IDs to check. #### Callback Parameters - **err** (Error) - An error object if the operation failed. - **availability** (object) - An object mapping each app ID to a boolean indicating its availability. ``` -------------------------------- ### player.seek Source: https://context7.com/thibauts/node-castv2-client/llms.txt Seeks the current media to a specified position in seconds. ```APIDOC ## player.seek(currentTime, callback) ### Description Seeks the current media to the given `currentTime` in seconds. ### Parameters #### currentTime - **currentTime** (number) - Required - The target playback time in seconds. #### Callback - **callback** (function) - Called after seeking or if an error occurs. - **err** - Error object if seeking failed. - **status** (object) - The status object of the player after seeking. - **currentTime** (number) - The new current playback time in seconds. ### Example ```javascript player.load(media, { autoplay: true }, function(err, status) { if (err) return console.error(err); // Seek to 2 minutes after 5 seconds of playback setTimeout(function() { player.seek(2 * 60, function(err, status) { if (err) return console.error(err); console.log('Seeked to:', status.currentTime); // ~120 seconds }); }, 5000); }); ``` ``` -------------------------------- ### Load and play media using player.load() Source: https://context7.com/thibauts/node-castv2-client/llms.txt Loads a media item onto the Chromecast for playback. Requires media object with contentId, contentType, and streamType. Options like autoplay and currentTime can be provided. ```javascript client.launch(DefaultMediaReceiver, function(err, player) { var media = { contentId: 'http://commondatastorage.googleapis.com/gtv-videos-bucket/big_buck_bunny_1080p.mp4', contentType: 'video/mp4', streamType: 'BUFFERED', metadata: { type: 0, metadataType: 0, title: 'Big Buck Bunny', images: [{ url: 'http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/images/BigBuckBunny.jpg' }] } }; player.load(media, { autoplay: true, currentTime: 0 }, function(err, status) { if (err) return console.error('Load error:', err.message); console.log('Loaded. Player state:', status.playerState); // PLAYING }); }); ``` -------------------------------- ### Set Device Volume with client.setVolume Source: https://context7.com/thibauts/node-castv2-client/llms.txt Sets the device's volume level or mute state. Use `{ level: 0.0–1.0 }` to adjust volume or `{ muted: true/false }` to toggle mute. The callback returns the updated volume object. ```javascript client.connect('192.168.1.42', function() { // Set volume to 50% client.setVolume({ level: 0.5 }, function(err, volume) { if (err) return console.error(err); console.log('Volume set to:', volume.level); // 0.5 }); // Mute the device client.setVolume({ muted: true }, function(err, volume) { if (err) return console.error(err); console.log('Muted:', volume.muted); // true }); }); ``` -------------------------------- ### client.getSessions Source: https://context7.com/thibauts/node-castv2-client/llms.txt Retrieves a list of active application sessions on the device. ```APIDOC ## client.getSessions(callback) ### Description Returns an array of currently running application sessions on the device. This is equivalent to accessing `status.applications` from the `getStatus` method. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Method Get Sessions ### Endpoint N/A (Method call) ### Request Example ```javascript client.connect('192.168.1.42', function() { client.getSessions(function(err, sessions) { if (err) return console.error(err); sessions.forEach(function(session) { console.log('App:', session.displayName, '| Session:', session.sessionId); }); client.close(); }); }); ``` ### Response #### Success Response (Callback) - `err` (Error): An error object if the request failed. - `sessions` (Array): An array of session objects, each containing details like `displayName` and `sessionId`. #### Response Example ```json [ { "appId": "CC1AD845", "displayName": "YouTube", "namespaces": [ { "name": "urn:x-cast:com.google.cast.media" } ], "sessionId": "some-session-id", "statusText": "", "transportId": "some-transport-id" } ] ``` ``` -------------------------------- ### player.play Source: https://context7.com/thibauts/node-castv2-client/llms.txt Resumes playback of a paused media session. ```APIDOC ## player.play(callback) ### Description Resumes a paused media session. ### Parameters #### Callback - **callback** (function) - Called after playback is resumed or if an error occurs. - **err** - Error object if resuming failed. - **status** (object) - The status object of the player after resuming. ### Example ```javascript player.pause(function(err) { if (err) return console.error(err); console.log('Paused'); setTimeout(function() { player.play(function(err, status) { if (err) return console.error(err); console.log('Resumed. State:', status.playerState); // PLAYING }); }, 3000); }); ``` ``` -------------------------------- ### player.queueInsert Source: https://context7.com/thibauts/node-castv2-client/llms.txt Inserts new items into the currently playing queue. Options include `insertBefore` (item ID to insert before), `currentItemId`, `currentItemIndex`, and `currentTime`. ```APIDOC ## player.queueInsert(items, options, callback) — Insert items into the queue ### Description Inserts new items into the currently playing queue. ### Parameters #### items - **media** (object) - Required - Media item details. - **autoplay** (boolean) - Optional - Whether to autoplay. - **preloadTime** (number) - Optional - Time in seconds to preload. - **startTime** (number) - Optional - Start time in seconds. - **playbackDuration** (number) - Optional - Duration of playback in seconds. - **activeTrackIds** (array) - Optional - IDs of active tracks. #### options - **insertBefore** (string) - Optional - Item ID to insert before. - **currentItemId** (string) - Optional - The ID of the current item. - **currentItemIndex** (number) - Optional - The index of the current item. - **currentTime** (number) - Optional - The current playback time in seconds. #### callback - **err** - Error object if an error occurred. - **status** - Status object of the player. ### Request Example ```javascript var newItem = { autoplay: true, preloadTime: 4, startTime: 0, activeTrackIds: [], media: { contentId: 'http://example.com/bonus-track.mp3', contentType: 'audio/mpeg', streamType: 'BUFFERED', metadata: { metadataType: 3, title: 'Bonus Track' } } }; player.queueInsert([newItem], { insertBefore: 2 }, function(err, status) { if (err) return console.error(err); console.log('Item inserted into queue. State:', status.playerState); }); ``` ``` -------------------------------- ### Load Media with Subtitle Tracks Source: https://context7.com/thibauts/node-castv2-client/llms.txt Configure and load media with VTT subtitle tracks using the DefaultMediaReceiver. Ensure media and subtitle files are served from CORS-enabled hosts. Subtitle tracks can be activated, deactivated, and styled during playback. ```javascript var media = { contentId: 'http://example.com/video.mp4', contentType: 'video/mp4', streamType: 'BUFFERED', textTrackStyle: { backgroundColor: '#000000FF', foregroundColor: '#FFFFFFFF', edgeType: 'DROP_SHADOW', edgeColor: '#00000099', fontScale: 1.2, fontStyle: 'BOLD', fontFamily: 'Droid Sans', fontGenericFamily: 'SANS_SERIF', windowType: 'ROUNDED_CORNERS', windowRoundedCornerRadius: 5 }, tracks: [ { trackId: 1, type: 'TEXT', trackContentId: 'http://example.com/subtitles-en.vtt', trackContentType: 'text/vtt', name: 'English', language: 'en-US', subtype: 'SUBTITLES' }, { trackId: 2, type: 'TEXT', trackContentId: 'http://example.com/subtitles-fr.vtt', trackContentType: 'text/vtt', name: 'French', language: 'fr-FR', subtype: 'SUBTITLES' } ] }; // Load with English subtitles active player.load(media, { autoplay: true, activeTrackIds: [1] }, function(err, status) { if (err) return console.error(err); console.log('Playing with subtitles. State:', status.playerState); // Switch to French subtitles during playback player.media.sessionRequest({ type: 'EDIT_TRACKS_INFO', activeTrackIds: [2] }); // Turn off subtitles player.media.sessionRequest({ type: 'EDIT_TRACKS_INFO', activeTrackIds: [] }); // Update subtitle style during playback player.media.sessionRequest({ type: 'EDIT_TRACKS_INFO', textTrackStyle: { fontScale: 1 } }); }); ``` -------------------------------- ### Launch DefaultMediaReceiver and listen for status updates Source: https://context7.com/thibauts/node-castv2-client/llms.txt Connects to a Chromecast device and launches the DefaultMediaReceiver application. It then sets up a listener to log player status updates. ```javascript var Client = require('castv2-client').Client; var DefaultMediaReceiver = require('castv2-client').DefaultMediaReceiver; var client = new Client(); client.connect('192.168.1.42', function() { client.launch(DefaultMediaReceiver, function(err, player) { if (err) return console.error(err); player.on('status', function(status) { // Broadcast status updates: playerState, currentTime, media info, etc. console.log('Player state:', status.playerState); }); }); }); ``` -------------------------------- ### Media Controller Actions Source: https://context7.com/thibauts/node-castv2-client/llms.txt Control media playback with `MediaController`. Load media, play, pause, seek, stop, and manage the media queue. It tracks the `currentSession` and emits `status` events for player state changes. ```javascript var MediaController = require('castv2-client').MediaController; var media = sender.createController(MediaController); media.on('status', function(status) { console.log('Media status broadcast:', status.playerState, '@', status.currentTime); }); media.load( { contentId: 'http://example.com/video.mp4', contentType: 'video/mp4', streamType: 'BUFFERED' }, { autoplay: true }, function(err, status) { if (err) return console.error(err); console.log('Loaded. SessionId:', status.mediaSessionId); } ); ``` -------------------------------- ### player.pause Source: https://context7.com/thibauts/node-castv2-client/llms.txt Pauses the currently playing media session. ```APIDOC ## player.pause(callback) ### Description Pauses the currently playing media session. ### Parameters #### Callback - **callback** (function) - Called after playback is paused or if an error occurs. - **err** - Error object if pausing failed. - **status** (object) - The status object of the player after pausing. - **currentTime** (number) - The current playback time in seconds when paused. ### Example ```javascript player.load(media, { autoplay: true }, function(err, status) { setTimeout(function() { player.pause(function(err, status) { if (err) return console.error(err); console.log('Paused at:', status.currentTime, 'seconds'); }); }, 5000); }); ``` ``` -------------------------------- ### Insert Item into Queue with player.queueInsert Source: https://context7.com/thibauts/node-castv2-client/llms.txt Inserts new items into the currently playing queue. Specify the item to insert and optionally an item ID to insert before. ```javascript var newItem = { autoplay: true, preloadTime: 4, startTime: 0, activeTrackIds: [], media: { contentId: 'http://example.com/bonus-track.mp3', contentType: 'audio/mpeg', streamType: 'BUFFERED', metadata: { metadataType: 3, title: 'Bonus Track' } } }; player.queueInsert([newItem], { insertBefore: 2 }, function(err, status) { if (err) return console.error(err); console.log('Item inserted into queue. State:', status.playerState); }); ``` -------------------------------- ### player.queueUpdate Source: https://context7.com/thibauts/node-castv2-client/llms.txt Updates metadata or playback settings of existing queue items in-place. Each item in `items` must include `itemId`. Options include `currentItemId`, `jump` (integer to skip forward/backward), `repeatMode`, and `currentTime`. ```APIDOC ## player.queueUpdate(items, options, callback) — Update queue items ### Description Updates metadata or playback settings of existing queue items in-place. ### Parameters #### items - **itemId** (string) - Required - The ID of the item to update. - **media** (object) - Optional - Media item details. - **autoplay** (boolean) - Optional - Whether to autoplay. - **preloadTime** (number) - Optional - Time in seconds to preload. - **startTime** (number) - Optional - Start time in seconds. - **playbackDuration** (number) - Optional - Duration of playback in seconds. - **activeTrackIds** (array) - Optional - IDs of active tracks. #### options - **currentItemId** (string) - Optional - The ID of the current item. - **jump** (number) - Optional - Integer to skip forward/backward. - **repeatMode** (string) - Optional - The repeat mode for the queue. - **currentTime** (number) - Optional - The current playback time in seconds. #### callback - **err** - Error object if an error occurred. - **status** - Status object of the player. ### Request Example ```javascript // Update the title metadata of item ID 4 player.queueUpdate( [{ itemId: 4, autoplay: true, preloadTime: 3, startTime: 0, activeTrackIds: [], media: { contentId: 'http://example.com/track.mp3', contentType: 'audio/mpeg', streamType: 'BUFFERED', metadata: { metadataType: 3, title: 'Updated Title' } } }], { currentItemId: 4 }, function(err, status) { if (err) return console.error(err); console.log('Queue item updated. State:', status.playerState); } ); ``` ``` -------------------------------- ### Resume playback using player.play() Source: https://context7.com/thibauts/node-castv2-client/llms.txt Resumes a paused media session. This is typically used after calling player.pause(). ```javascript player.pause(function(err) { if (err) return console.error(err); console.log('Paused'); setTimeout(function() { player.play(function(err, status) { if (err) return console.error(err); console.log('Resumed. State:', status.playerState); // PLAYING }); }, 3000); }); ``` -------------------------------- ### Connection Controller Usage Source: https://context7.com/thibauts/node-castv2-client/llms.txt The `ConnectionController` manages the CASTV2 virtual connection. Use its `connect()` and `disconnect()` methods to establish and close the connection, and listen for the `disconnect` event. ```javascript var ConnectionController = require('castv2-client').ConnectionController; // Typically used internally by Application and PlatformSender. // Manual usage example within a custom Sender: var connController = sender.createController(ConnectionController); connController.on('disconnect', function() { console.log('Remote side closed the virtual connection'); }); connController.connect(); // sends CONNECT // later: connController.disconnect(); // sends CLOSE ``` -------------------------------- ### Request/Response Controller Source: https://context7.com/thibauts/node-castv2-client/llms.txt Use `RequestResponseController` for channels that involve sending a request and waiting for a specific response. It automatically handles request IDs and response matching. ```javascript var RequestResponseController = require('castv2-client').RequestResponseController; var util = require('util'); function MyRRController(client, sourceId, destinationId) { RequestResponseController.call(this, client, sourceId, destinationId, 'urn:x-cast:com.example.rr'); } util.inherits(MyRRController, RequestResponseController); MyRRController.prototype.ping = function(callback) { this.request({ type: 'PING' }, function(err, response) { if (err) return callback(err); callback(null, response); // response.type === 'PONG' }); }; ```