Getting Started with Brightcove Web & Smart TV SDK

This section provides the initial steps required to set up and begin using the Brightcove Web & Smart TV SDK.

Installing the SDK

You can install the Brightcove Web & Smart TV SDK using npm or directly from the Brightcove CDN.


Using npm:

Open your command line interface and run the following command to install the SDK:

npm install @brightcove/web-sdk


After installation, you can import the SDK using your preferred module system:

CommonJS

const { Player } = require('@brightcove/web-sdk');

ES Module

import { Player } from '@brightcove/web-sdk';

Using CDN

Alternatively, if you prefer to use the SDK from the CDN, include one of the following script tags in your HTML files:

CommonJS

<script src="https://players.brightcove.net/sdk/v1/web-sdk/playback/index.cjs.js"></script>

ES Module

<script type="module" src="https://players.brightcove.net/sdk/v1/web-sdk/playback/index.es.js"></script>

IIFE (Immediately Invoked Function Expression)

<script src="https://players.brightcove.net/sdk/v1/web-sdk/playback/index.iife.min.js"></script>

Specifying a Version

To specify a version in the CDN URL:

  • Use v{major} to include the latest patch within a major version.
  • Use v{major}.{minor} to include the latest patch within a minor version.
  • Use v{major}.{minor}.{patch} to include a specific version.

For example


<script src="https://players.brightcove.net/sdk/v1/web-sdk/playback/index.iife.min.js"></script>
 <script src="https://players.brightcove.net/sdk/v1.1/web-sdk/playback/index.iife.min.js"></script>
 <script src="https://players.brightcove.net/sdk/v1.1.1/web-sdk/playback/index.iife.min.js"></script>

Import the Player

Playback-Only

For applications that only require playback functionality, and no additional UI features:

import { Player } from '@brightcove/web-sdk/playback';
      

Playback with UI

For applications that need playback functionality along with a UI, use the following player entry point:

import { Player } from '@brightcove/web-sdk/ui';
 import '@brightcove/web-sdk/ui/styles';
        

Initializing the Player

Once the SDK is installed, you can create a media player to embed in your application. By following these steps, you will have a basic video player set up using the Brightcove Web & Smart TV SDK.

  1. Initialize the Player: Set up the player with your Brightcove account details:

    const player = new Player({
      // Account ID parameter is required to initialize a player
      accountId: '<ACCOUNT_ID>',
     });
    
  2. Attach the player to a mount root (DOM element in the page):

    const root = document.querySelector('#player-mount-root');
     player.attach(root);
            
  3. Dynamically update params in the player configuration:

    player.updateConfiguration({
      brightcove: {
        policyKey: '<POLICY_KEY>'
      },
      ui: {
        language: 'en',
        playsinline: false
      }
    });
                        

Loading Media

Video Cloud VOD

Load media into your project by following these steps:

  1. Initialize the Player: Create a new instance of the Player.

    const player = new Player({accountId: '<ACCOUNT_ID>'});
    
    player.updateConfiguration({
      brightcove: {
        policyKey: '<POLICY_KEY>'
      },
    });
          
  2. Create a Function to Load Video: Define an asynchronous function to load video metadata using the video ID.

    async function loadVideo(videoId) {
    // you can abort a request by calling abort()
        const { abort, promise } = player.getVideoByIdFromPlaybackApi({ videoId: '<VIDEO_ID>' });
    
        try {
            let brightcoveVideoModel = await promise;
    
            player.loadBrightcoveVideoModel(brightcoveVideoModel);
        } catch (error) {
            console.error('Error loading video:', error);
        }
    }
    
  3. Call the loadVideo function with your specific video ID to load the video into the player.

    loadVideo('<VIDEO_ID>');
    
    

Video Cloud Playlist

Integrate playlists into your project by following these steps:

  1. Initialize the Player: Create a new instance of the Player.

    const player = new Player({accountId: '<ACCOUNT_ID>'});
    
    player.updateConfiguration({
      brightcove: {
        policyKey: '<POLICY_KEY>'
      },
    });
  2. Create a Function to Load Playlist: Define an asynchronous function to load a playlist using the playlist ID.

    async function loadPlaylist(playlistId) {
    // you can abort request by calling abort()
        const { abort, promise } = player.getPlaylistByIdFromPlaybackApi({ playlistId });
    
        try {
            const playlistModel = await promise;
            const playlistManager = player.getPlaylistManager();
    
            // Create playlist object
            const playlist = playlistManager.createPlaylistFromBrightcoveVideoModels(playlistModel.videos);
    
            // Pass the playlist object to the PlaylistManager
            playlistManager.setPlaylist(playlist);
    
            // Load the first playlist item
            player.loadBrightcoveVideoModel(playlist.getCurrentItem());
        } catch (error) {
            console.error('Error loading playlist:', error);
        }
    }
    
  3. Call the loadPlaylist function with your specific playlist ID to load the playlist into the player.

    loadPlaylist('<PLAYLIST_ID>');
    
    
    
  4. Create a function to advance to the next item.

    function advanceToNextItem() {
      const playlistManager = player.getPlaylistManager();
      const playlist = playlistManager.getPlaylist();
    
      // Advance to the next item
      playlist.moveToNext();
      player.loadBrightcoveVideoModel(playlist.getCurrentItem());
    }
    
    advanceToNextItem();

Remote Source

Integrate a remote source into your project by following these steps:

  1. Initialize the Player: Create a new instance of the Player.

    const player = new Player({
    // accountId is still required even when loading remote media
        accountId: '<ACCOUNT_ID>',
    });
  2. Define the Remote Video Source: Define the remote video source URL.

    const source = {
        url: 'https:'
    };
    
  3. Load the Remote Video: Load the remote video source.

    player.loadRemoteVideo(source);  
    

IntegrationsManager

The IntegrationsManager class is designed to manage various integrations within the SDK, such as pinning, thumbnails, IMA ads, and more. See. It allows you to register, deregister, and access different integration factories, providing a flexible way to enhance your video player with additional features.

Example Usage

Below is an example of how to use the IntegrationsManager to register integrations and use them within your Player instance.

  1. Import Necessary Modules: Import the required modules from the SDK.

    import { Player, IntegrationsManager } from '@brightcove/web-sdk';
     import { PinningIntegrationFactory } from '@brightcove/web-sdk/integrations/pinning';
     import { ThumbnailsIntegrationFactory } from '@brightcove/web-sdk/integrations/thumbnails';
     import '@brightcove/web-sdk/ui/styles';
     import '@brightcove/web-sdk/integrations/pinning/styles';
     import '@brightcove/web-sdk/integrations/thumbnails/styles';
  2. Register Integrations: Register the integrations before creating the player instance.

    IntegrationsManager.registerPinningIntegrationFactory(PinningIntegrationFactory);
     IntegrationsManager.registerThumbnailsIntegrationFactory(ThumbnailsIntegrationFactory);
    
  3. Initialize the Player with Integrations: Create a new instance of the Player and include the integrations with their configuration options.

    const player = new Player({accountId: '<ACCOUNT_ID>'});
    
    player.updateConfiguration({
    // Integrations can have their own configuration options
      integrations: {
        pinning: {
          posX: 'left',
          posY: 'top',
          closeable: true
        }
      }
    });
    
  4. Attach the Player to the DOM: Specify the DOM element where the player should be attached.

    const root = document.querySelector('#player-mount-root');
     player.attach(root);          
    
  5. Access Individual Integrations: Use the IntegrationsManager to access and control specific integrations.

    const { pinningIntegration } = player.getIntegrationsManager();         
    
  6. Perform Integration-Specific Operations provided by the integration.

    pinningIntegration.togglePinning();       
    

NetworkingManager

The NetworkingManager is used to hook into the SDK's request/response cycle and allows you to intercept and manipulate network requests and responses the player makes, enabling a wide range of custom behaviors and optimizations.

The NetworkingManager provides two main functionalities:

  • Request Interceptors: These allow you to intercept and modify outgoing requests before they are sent to the server.

  • Response Interceptors: These allow you to intercept and modify incoming responses before they are processed by the player.

To use the NetworkingManager follow these steps:

  1. Initialize the NetworkingManager

    const networkingManager = player.getNetworkingManager();      
          
  2. Add a Request Interceptor: Add a request interceptor to modify or log the outgoing requests.

    networkingManager.addRequestInterceptor(Player.RequestType.HlsPlaylist, (request) => {
        console.log('HLS Playlist request interceptor', request);
        return request;
    });      
          
  3. Add a Response Interceptor: Add a response interceptor to modify or log the incoming responses.

    networkingManager.addResponseInterceptor(Player.RequestType.HlsPlaylist, (response) => {
        console.log('HLS Playlist response interceptor', response);
        return response;
    });   
          

UiManager

The UiManager creates and manages UI Components. All SDK UI Components extend the UiComponent class, which has an extensive API.

See the UiComponentDependencies interface for the basic list of options that can be passed to components.


Overriding Default Components

Modify existing components to better suit your application's needs.

  1. Import Required Modules

    import { UiManager, BigPlayButtonUiComponent, UiComponentType } from '@brightcove/web-sdk/ui';
          
  2. Create a Custom UI Component

    class CustomPlayButton extends BigPlayButtonUiComponent {
      // ... custom play button code
    }
          
  3. Override the Default Component: override the default BigPlayButton with the CustomPlayButton

    UiManager.overrideDefaultComponent(UiComponentType.BigPlayButton, CustomPlayButton);
          

Custom Components

By using the BaseUiComponent class, you can add unique features and tailor the player interface to better fit your application requirements.

To apply Custom Components following these steps:

  1. Import BaseUiComponent:

    import { BaseUiComponent } from '@brightcove/web-sdk/ui';
  2. Initialize UI Manager and Player Component:

    
    const uiManager = player.getUiManager();
     const playerComponent = uiManager.getPlayerContainerUiComponent();
    
  3. Create a DOM element:

    const customElement = document.createElement('div');
    
  4. Create a new custom UI component:

    const customComponent = new BaseUiComponent({
       // Add a unique name
       name: 'CustomUiComponent',
       componentOptions: {
         // Pass the custom DOM element as an option
         el: customElement,
       },
     });
          
  5. Add the Custom Component to the Player:

    playerComponent.addChild(customComponent);
  6. (Optional) Add the Custom Component to Another Component : (for example the ControlBar)

    const controlBarComponent = playerComponent.getChild('controlBar');
     controlBarComponent.addChild(customComponent);
            

PlaylistManager

The PlaylistManager provides methods for creating playlists, managing the current playing item, and navigating through the playlist items.

To use the PlaylistManager follow these steps:

  1. Initialize PlaylistManager:

    const playlistManager = player.getPlaylistManager();
  2. Create a Playlist from a Playback API Response:

    const videoCloudPlaylist = playlistManager.createPlaylistFromBrightcoveVideoModels(
      /* Array<BrightcoveVideoModel> */
    );
  3. Create a Playlist from Remote Sources: Alternatively, create a playlist using remote media sources.

    const remotePlaylist = playlistManager.createPlaylistFromRemoteSources(
       /* Array<Source> */
     );
  4. Set the Playlist in the PlaylistManager:

    playlistManager.setPlaylist(/* videoCloudPlaylist | remotePlaylist */);
          
  5. Load the First Playlist Item:

    player.loadBrightcoveVideoModel(playlist.getCurrentItem());
  6. Navigate Through the Playlist: Use the next methods to navigate through the playlist items.

    • Move to the next item:

      playlist.moveToNext();
                
    • Move to the previous item:

      playlist.moveToPrevious();
                
    • Move to a specific item:

      playlist.moveTo(/* index number */);
                
    • Shuffle the playlist:

      playlist.shuffle();
                
  7. Load the new current item: Load the newly selected item in the playlist.

    player.loadBrightcoveVideoModel(playlist.getCurrentItem());
          

Events

To handle events, add or remove event listeners follow these steps:

  1. Handle the First Emission of an Event: If you want to handle only the first occurrence of an event, use the once method.

    player.once(Player.Event.PlayerPlaying, (event) => {
        console.log('PlayerPlaying event: ', event);
    });
  2. Handle Every Emission of an Event: To handle every emission of an event, use the addEventListener method. Below is an example of handling the PlayerQualityLevelsChanged event:

    // Define the event handler function
    const handlePlayerQualityLevelsChanged = (event) => {
        console.log('PlayerQualityLevelsChanged event: ', event);
    };
    
    // Handle every emission of the PlayerQualityLevelsChanged event
    player.addEventListener(Player.Event.PlayerQualityLevelsChanged, handlePlayerQualityLevelsChanged);
    
  3. Remove Specific Event Listeners: To remove a specific event listener, use the removeEventListener method.

    
    player.removeEventListener(Player.Event.PlayerQualityLevelsChanged, handlePlayerQualityLevelsChanged);
          
    
  4. Remove All Listeners for a Specific Event: To remove all listeners for a specific event, use the removeAllEventListenersForType method.

    
    player.removeAllEventListenersForType(Player.Event.PlayerQualityLevelsChanged);      
    
  5. Remove All Event Listeners: To remove all event listeners for all events, use the removeAllEventListeners method:

    
    player.removeAllEventListeners();   
    

Errors

To listen for error events and check the player's current error state, follow these steps:

  1. Listening for Error Events:

    this.player.addEventListener(Player.Event.PlayerError, (event) => {
      const error = event.error;
    
      console.log('An error occurred:', error);
    });

Styling

To apply CSS for UI features follow these steps:

  1. Import the Player Class:

    import Player from '@brightcove/web-sdk/ui';
  2. Import the CSS for the Player Class:

    import '@brightcove/web-sdk/ui/styles';
  3. Importing Integration-Specific Styles: you must import the styles specific to that integration from
     @brightcove/web-sdk/integrations/<integration-name>/styles
    If you are integrating with a specific feature like pinning, follow this pattern:

    import '@brightcove/web-sdk/integrations/pinning/styles';

CSS Variables

The CSS from @brightcove/web-sdk/ui/styles comes with a set of preset CSS variables to control certain aspects of the player's styling. These CSS variables can be overridden by resetting the value.

.bc-sdk {
     /* Override the default control bar color */
     --bc-sdk-control-bar-color: red;
 }

The following are the available CSS variables, along with their default values:

Variable Default Value Description
--bc-sdk-control-color #fff The color of buttons and text.
--bc-sdk-progress-color #80888c The color of the progress bar.
--bc-sdk-control-bar-transparency 0.45 The transparency of the background color of the control bar and the big play button.
--bc-sdk-control-bar-color rgba(0, 0, 0, var(--bc-sdk-control-bar-transparency)) The background color of the control bar and the big play button.
--bc-sdk-big-play-button--border none The border of the big play button.
--bc-sdk-big-play-button--width 2em The width of the big play button.
--bc-sdk-big-play-button--height 2em The height of the big play button.

Spatial Navigation

spatialNavigation enhances user experience and accessibility on Smart TV devices by enabling navigation through interactive elements within the player using remote control arrow keys.

Enable Spatial Navigation

  1. Import the required Player class and associated styles.

    import { Player } from '@brightcove/web-sdk/ui';
     import '@brightcove/web-sdk/styles';
  2. Initialize a UI-enabled player for Spatial Navigation.

    const player = new Player({ accountId: '<ACCOUNT_ID>' });
    
     player.updateConfiguration({
       ui: {
         spatialNavigation: {
           // Enable Spatial Navigation
           enabled: true,
     
           // Enable horizontal navigation seek functionality, using right and left RCU arrow keys.
           horizontalSeek: true,
         }
       }
     });
  3. Retrieve the Spatial Navigation Manager.

    const spatialNavigationManager = player.getSpatialNavigationManager();
  4. Manage Spatial Navigation Events. The SpatialNavigationManager allows you to start, pause, resume, and stop listening for keydown events.

    // Start listening for keydown events
    spatialNavigationManager.start();
    
    // Pause listening for keydown events without removing listeners
    spatialNavigationManager.pause();
    
    // Resume listening for keydown events after pausing
    spatialNavigationManager.resume();
    
    // Disable Spatial Navigation by removing all keydown listeners
    spatialNavigationManager.stop();

Spatial Navigation Events

The Web & Smart TV SDK provides two key events for spatial navigation:

  1. Player.Event.SpatialNavigation.EndOfFocusableComponents: Fired when there are no more focusable components available in the specified direction within the player interface.

  2. Player.Event.SpatialNavigation.FocusableComponentsChanged: Fired when the list of focusable components changes.

Localizations

Localization is a crucial aspect of developing a user-friendly video player that meets the needs of a diverse, global audience.

Support for multiple languages and localizations can be included as follows:

  1. Import general player localizations:

    import mainJapanese from '@brightcove/web-sdk/ui/languagePacks/ja';
          
  2. Import integration-specific localizations:

    import ssaiJapanese from '@brightcove/web-sdk/integrations/ssai/languagePacks/ja';
          
  3. Initialize the UI Manager:

    const uiManager = player.getUiManager();
          
  4. Add the Language Pack to the UI Manager: Use the addLanguagePack method of the UI manager to add the imported language pack:

    uiManager.addLanguagePack('ja', mainJapanese);
     uiManager.addLanguagePack('ja', ssaiJapanese);
          

Sample Implementations

To help you quickly get up to speed with the Brightcove Web & Smart TV SDK, we offer several sample implementations. These examples demonstrate various features and use cases, providing a hands-on way to learn how to use the SDK effectively.

Explore a variety of sample implementations by visiting the following links: