castv2-client

repository·master·Indexed 20 days ago

https://github.com/thibauts/node-castv2-client

A Node.js client implementation of the Google Cast (CASTV2) protocol. It allows developers to discover Chromecast devices and control media playback or custom applications. The library provides a Client for device connection and a DefaultMediaReceiver for loading media, controlling playback (play, pause, stop, seek), and managing the media queue.

Tokens
2.7K
Snippets
6
Records
9
Agent score
71%

What's inside castv2-client

  1. How the castv2-client architecture works

    master

    The castv2-client library provides a high-level implementation of the CASTV2 protocol. It is structured around several key abstractions:

    • Client: The main entry point used to connect to a Chromecast device via its host IP.
    • Application: A base class for defining Chromecast applications. The library provides DefaultMediaReceiver as a ready-to-use sender app.
    • Controllers: Implementations of basic protocols (found in the controllers directory) that allow you to interact with the application (e.g., controlling media playback).

    This structure allows developers to easily implement custom senders by extending the Application base class and using the provided controllers.

  2. Install castv2-client

    master

    Install the castv2-client module using npm. If you are on Windows and want to avoid native module dependencies, use the --no-optional flag.

    $ npm install castv2-client

    On windows, to avoid native modules dependencies, use:

    $ npm install castv2-client --no-optional
  3. Launch a media stream on a Chromecast device

    master

    To play media on a Chromecast, you must first discover the device (e.g., using mdns), connect a new Client instance to the device's host, and then launch the DefaultMediaReceiver application. Once launched, you receive a player object which you can use to load media and control playback via methods like seek.

    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();
      });
    
    }
  4. Manage the media queue with DefaultMediaReceiver

    master

    The DefaultMediaReceiver allows you to manipulate the playback queue using the following methods:

    • queueLoad(items, options, callback): Loads a new queue.
    • queueInsert(items, options, callback): Inserts items into the queue.
    • queueRemove(itemIds, callback): Removes items by their IDs.
    • queueReorder(itemIds, callback): Reorders items in the queue.
    • queueUpdate(items, callback): Updates existing items in the queue.
  5. Use DefaultMediaReceiver for media playback

    master

    The DefaultMediaReceiver class is used to interact with the default media receiver application on a Chromecast device, typically for playing media URLs.

    const { DefaultMediaReceiver } = require('node-castv2-client');
    
    // Use DefaultMediaReceiver to control media playback
    const receiver = new DefaultMediaReceiver(client);
  6. Use DefaultMediaReceiver to control media playback

    master

    The DefaultMediaReceiver is a pre-configured sender for the standard Chromecast Default Media Receiver application (App ID: CC1AD845). It provides a high-level API to load media, control playback (play, pause, stop, seek), and manage the playback queue. It wraps a MediaController to handle these operations.

    // Assuming 'client' and 'session' are already initialized
    const DefaultMediaReceiver = require('castv2-client').DefaultMediaReceiver;
    const receiver = new DefaultMediaReceiver(client, session);
    
    // Load a media item
    receiver.load({
      contentId: 'http://example.com/video.mp4',
      contentType: 'video/mp4',
      streamType: 'progressive'
    }, {}, (err) => {
      if (err) console.error(err);
      else console.log('Media loaded');
    });
    
    // Control playback
    receiver.play((err) => {
      if (err) console.error(err);
    });
    
    // Listen for status changes
    receiver.on('status', (status) => {
      console.log('Current status:', status);
    });
  7. Initialize a Chromecast connection with Client

    master

    The Client class (also exported as PlatformSender) is the primary entrypoint for interacting with a Chromecast device using the CASTV2 protocol. It is used to establish a connection and manage communication with the device.

    const { Client } = require('node-castv2-client');
    
    // Usage depends on the internal implementation of Client
    const client = new Client(device, options);
  8. Access specialized controllers

    master

    The library exports several specialized controllers to manage different aspects of the CASTV2 protocol and device interaction. These are typically used in conjunction with a Client or Application instance to handle specific logic like heartbeats, media control, or connection management.

    const controllers = require('node-castv2-client');
    
    // Available controllers:
    // controllers.Controller
    // controllers.JsonController
    // controllers.RequestResponseController
    // controllers.ConnectionController
    // controllers.HeartbeatController
    // controllers.ReceiverController
    // controllers.MediaController
  9. DefaultMediaReceiver API Reference

    master

    The following methods are available on an instance of DefaultMediaReceiver:

    MethodParametersDescription
    getStatus(callback)callbackRetrieves the current media status
    load(media, options, callback)media, options, callbackLoads a specific media item
    play(callback)callbackStarts playback
    pause(callback)callbackPauses playback
    stop(callback)callbackStops playback
    seek(currentTime, callback)currentTime, callbackSeeks to a specific time
    queueLoad(items, options, callback)items, options, callbackLoads a new queue
    queueInsert(items, options, callback)items, options, callbackInserts items into the queue
    queueRemove(itemIds, callback)itemIds, callbackRemoves items by ID
    queueReorder(itemIds, callback)itemIds, callbackReorders items
    queueUpdate(items, callback)items, callbackUpdates items in the queue