JavaScript API access

<html>
    <body>
        <div style="width: 890px; height: 500px; background: black;" id="PLAYER_DOM_ID"></div>
        <script type="text/javascript">
            var config = {
                dataProvider: {
                    source: [
                        { url: "https://example.com/video.mp4" }
                    ]
                }
            };

            /** find player container in html DOM tree. */
            var element = document.getElementById("PLAYER_DOM_ID");

            /** create player */
            var player = window.bradmax.player.create(element, config);

            /** get javascript api */
            var jsapi;

            /** player version >= v2.14.285 */
            if (player.hasOwnProperty('api'))
                jsapi = player.api;

            /** player version < v2.14.285 */
            if (jsapi === null)
                jsapi = player.modules.JavascriptApi;

            /** get destroy player api */
            var destroyPlayer = window.bradmax.player.destroy;

            /** handle player close event */
            jsapi.on("close", function() {
                destroyPlayer(player);
            });
        </script>
    </body>
</html>

API methods:

Method nameInput typeOutput typeDescription
bradmax.player.create(config)objectobjectCreates player instance for provided configuration.
bradmax.player.destroy(playerInstance)objectvoidDestroy/remove provided player instance and release used resources.
bradmax.player.close(playerInstance)objectvoidDestroy/remove provided player instance (stopping playback), but HTML placeholder is kept in HTML DOM for future reuse.
bradmax.player.getVersion()-stringGet player version from SDK
getVersion()-stringGet player version from player instance
play()-voidStarts media playback.
pause()-voidPause media playback.
playPause()-voidToggle between play and pause. If player is in ‘pause’ state, this command will start media playback. If player is in ‘play’ state, this command will pause media playback.
seek(timeSec)numbervoidSeek media to time position in seconds.
seekRelative(timeOffsetSec)numbervoidSeek relative to current position with provided offset (positive: forward, negative: backward)
setVolume(value)numbervoidSet volume, accept value in range from 0 to 1, example: 0.75.
setMute(value)booleanvoidMute player when “true” passed. Unmutes with previous volume on “false” value.
on(actionName,handler)string, functionvoidAdd event listener for supported actions. Supported action names: "close".
add(eventClassName,handler)string, functionvoidAdd event listener.
addOnce(eventClassName,handler)string, functionvoidAdd single event listener. It is only once triggered, then removed.
remove(eventClassName,handler)string, functionvoidRemove event listener.
toggleFullscreen()-voidToggle player fullscreen mode. Notice: This function has to be called in user gesture scope (onClick/onTap) for proper work. Same limit as calling play() for mobile devices.
repaint()-voidForce player to repaint UI. Solves problems, when player was hidden/shown by external JS and sometimes UI needs to be repainted.
pictureInPicture.isAvailable()-boolReturns if browser supports Picture-in-Picture mode for video.
pictureInPicture.enter()-voidTriggers entering Picture-in-Picture mode for selected player.
pictureInPicture.leave()-voidLeave Picture-in-Picture mode for selected player.
appGoingBackground()-voidNotify player that web app is moving to background.
appGoingForeground()-voidNotify player that web app is moving to foreground from background.
requestVideoQualityChange(qualityLevel)stringvoidRequest quality change to selected level eg. "0" - lowest, "-1" - auto


API events:


AdEvent:

AdEvent name (string)Description
AdEvent.adConnectionErrorThere was network issue with ad.
AdEvent.adCurrentTimeChangeAd playback time was updated.
AdEvent.adGroupCurrentTimeChangeAd group playback time was updated.
AdEvent.adCompleteSingle ad in ad break just completed.
AdEvent.adDisableControlsAd break is starting and player controls was hide.
AdEvent.adEnableControlsAd break ended and player controls were show.
AdEvent.adInStreamPlayingAd break (injected into main video stream) just started.
AdEvent.adInStreamEndAd break (injected into main video stream) just ended.
AdEvent.adInStreamClipPlayingInjected into main stream ad started in ad break.
AdEvent.adInStreamClipEndInjected into main stream ad ended in ad break.
AdEvent.adMediaErrorCannot play / decode video file for ad.
AdEvent.adPausedAd was paused.
AdEvent.adPlayingAd or ad break just started.
AdEvent.adSkipButtonShowAd skip button was shown (because of ad configuration).
AdEvent.adSkipClickAd skip button was clicked.


ControlEvent:

ControlEvent name (string)Description
ControlEvent.fullscreenFull screen mode was toggled.
ControlEvent.skinVolumePlayer volume was updated. Volume level in event.data field (0.0 - muted, 1.0 - full volume).
ControlEvent.skinPlayUser requested to play video, but it is not playing yet.
ControlEvent.skinPauseUser requested to pause video.
ControlEvent.skinPlayPauseUser requested to toggle between play / pause player state.


DataProviderEvent:

DataProviderEvent name (string)Description
DataProviderEvent.mediaMetadataDataNew media metadata is available. Details in event argument.
DataProviderEvent.adMetadataDataNew ad media metadata is available. Details in event argument.
DataProviderEvent.subtitleDataInfo about subtitles tracks.
DataProviderEvent.audioDataInfo about audio tracks.
DataProviderEvent.videoQualityDataInfo about available video/audio qualities.


VideoEvent:

VideoEvent name (string)TypeDescription
VideoEvent.accessDeniedstringAccess denied error occurred.
VideoEvent.bufferingStartstringVideo/Audio buffering just started.
VideoEvent.bufferingEndstringBuffering ended and playback can be continued.
VideoEvent.completestringMedia playback was completed.
VideoEvent.connectionErrorstringNetwork issue occurred - cannot connect with streaming server.
VideoEvent.currentTimeChangestringMedia playback current time was changed.
VideoEvent.durationChangestringMedia duration time was changed.
VideoEvent.loadErrorstringNetwork issue occurred.
VideoEvent.mediaErrorstringMedia decode issue - broken video or not compatible.
VideoEvent.mediaErrorFallbackTrystringPlayer fallback mechanism triggered - trying to resume interrupted playback.
VideoEvent.playbackPermamentErrorstringError occurred during playback and player was unable to solve it.
VideoEvent.playingstringMedia playback was started.
VideoEvent.pausedstringMedia playback was paused.
VideoEvent.seekingStartstringSeeking over video was started.
VideoEvent.seekingEndstringSeeking over video ended and playback can be continued.
VideoEvent.drmAuthenticationCompletestringDRM authentication complete - video can be decoded with provided keys
VideoEvent.drmAuthenticationErrorstringCannot decode video with provided keys or other error occurred related with authentication.
VideoEvent.drmAuthenticationNeededstringPlayer detect that video is DRM protected and decryption key will be needed.

API usage examples:

Example of events handling:

<html>
    <body>
        <div style="width: 890px; height: 500px; background: black;" id="PLAYER_DOM_ID"></div>
        <script type="text/javascript">
            var player = window.bradmax.player.create(document.getElementById("PLAYER_DOM_ID"), {
                dataProvider: {
                    source: [
                        { url: "https://example.com/video.mp4" }
                    ]
                }
            });
            function removePlayer() {
                window.bradmax.player.destroy(player);
            }

            var element = document.getElementById("player");
            var player = window.bradmax.player.create(element, playerConfig);
            var jsapi = player.api;
            /**
             * NOTE: if player version is lower than v2.14.285, api can be accessed as shown in next line:
             * var jsapi = player.modules.JavascriptApi;
            */
            jsapi.on("close", removePlayer);

            jsapi.play();
            jsapi.pause();
            jsapi.add("VideoEvent.paused", onPause);
            jsapi.add("VideoEvent.currentTimeChange", onCurrentTimeChange);
            jsapi.add("VideoEvent.complete", onComplete);
            jsapi.add("DataProviderEvent.mediaMetadataData", onNewMovieSet);

            /** movie data received by player */
            function onNewMovieSet(e) {
                jsapi.remove("VideoEvent.playing", onPlay);
                jsapi.addOnce("VideoEvent.playing", onFirstPlay);
            }

            /** first play event */
            function onFirstPlay(e) {
                jsapi.add("VideoEvent.playing", onPlay);
            }

            /** play event, does not triggered with first play */
            function onPlay(e) {
                alert(' bradmax player "onPlay" handler ');
            }

            /** pause event */
            function onPause(e) {
                alert(' bradmax player "onPause" handler ');
            }

            /** movie progress event */
            function onCurrentTimeChange(e) {
                alert(' bradmax player current time :' + e.data.currentTime);
            }

            /** movie complete event */
            function onComplete(e) {
                alert(' bradmax player "onComplete" handler ');
            }
        </script>
    </body>
</html>


Example of playing playlist:

<html>
    <body>
        <div style="width: 890px; height: 500px; background: black;" id="PLAYER_DOM_ID"></div>
        <script type="text/javascript">
            var config = {
                dataProvider: [
                {
                    title: "First video",
                    duration: 596.0,
                    source: [{ url: "https://example.com/video.m3u8" }]
                },
                {
                    title: "Second video",
                    duration: 734.097415,
                    source: [{ url: "https://example.com/video.mp4" }],
                    splashImages: [{ url: "https://example.com/startsplash.jpg" }]
                }]
            };
            var element = document.getElementById("PLAYER_DOM_ID");
            var player = window.bradmax.player.create(element, config);
        </script>
    </body>
</html>


NOTE: For proper playlist handling player has to be properly configured.

  1. Open player configurator page (open page: https://bradmax.com/client/panel/admin/player/list and create new player or select one for edition ).
  2. Select “Skin configuration” > "end splash".
  3. From available types choose “countdown” or “tiles”. For these types player will correctly handle playlist.


Example of player playlist with changing page on video change:

Below is example of player with playlist, where video is played on custom page. In such case only first video from playlist will be played by player on page. Next video from playlist will be played on custom player pages after user click on selected video. This playlist can be used for presenting recommended next video for user. First item from list is video, which will be played on current page.

<html>
    <body>
        <div style="width: 890px; height: 500px; background: black;" id="PLAYER_DOM_ID"></div>
        <script type="text/javascript">
            var media = {
                    dataProvider: [
                    // First video player on current page.
                    {
                        title: "First video",
                        duration: 596.0,
                        source: [{ url: "https://example.com/video.m3u8" }]
                    },
                    // Proposed videos, which after clicking will start on new page.
                    {
                        title: "Second video",
                        duration: 734.097415,
                        // Please define page, where player with autoplay will start playback of selected video.
                        mediaLandingPage: "https://example.com/#player_page_url_with_selected_media",
                        source: [{ url: "https://example.com/video.mp4" }],
                        splashImages: [{ url: "https://example.com/startsplash.jpg" }]
                    },
                    // Proposed video, which after clicking will start on new page.
                    {
                        title: "Third video",
                        duration: 734.097415,
                        // Please define page, where player with autoplay will start playback of selected video.
                        mediaLandingPage: "https://example.com/#player_page_url_with_selected_media_2",
                        source: [{ url: "https://example.com/video.mp4" }],
                        splashImages: [{ url: "https://example.com/startsplash.jpg" }]
                    }]
            };
            var element = document.getElementById("PLAYER_DOM_ID");
            var player = window.bradmax.player.create(element, media);
        </script>
    </body>
</html>


NOTE: For proper playlist handling player has to be properly configured.

  1. Open player configurator page (open page: https://bradmax.com/client/panel/admin/player/list and create new player or select one for edition ).
  2. Select “Skin configuration” > "end splash".
  3. From available types choose “countdown” or “tiles”. For these types player will correctly handle playlist.


Example how to change player quality via player JavaScript API

Below is example how to obtain list of video/audio qualities from player and how to select one using JavaScript API. Video & audio qualities are “merged” into single list even when internally they are available independently - for example for MPEG-DASH it is possible to select audio & video qualities independently. For user ease video/audio qualities are merged into single list and audio is automatically “preselected” for each video quality.

<html>
    <body>
        <div style="width: 890px; height: 500px; background: black;" id="PLAYER_DOM_ID"></div>
        <script type="text/javascript">
            var media = {
                    dataProvider: [{
                        title: "First video",
                        duration: 596.0,
                        source: [{ url: "https://example.com/video.m3u8" }]
                    }]
            };
            var element = document.getElementById("PLAYER_DOM_ID");
            var player = window.bradmax.player.create(element, media);
            var jsapi = player.modules.JavascriptApi;

            function onVideoQualitiesInfo(event) {
                // Display info about video qualites
                // Quality level is in event.data[].data in video quality record.
                //{
                //    "label": "176p",   // user label for quality description
                //    "data": "0",       // key used for quality identification. Use it for calling jsapi.requestVideoQualityChange().
                //    "height": 176,     // Video resolution height (it is scaled to whole player area).
                //    "width": 426,      // Video resolution width (it is scaled to whole player area).
                //    "bitrateKbps": 1280,  // Bitrate in Kbps.
                //    "active": false    // Indicates if such level is currently active/in-use or not.
                //}
                console.log(event.data);

                // Select lowest quality (lowest "0" highest some "N"). Mode auto quality selection got value "-1".
                // Notice: Arguments are numbers passed as string.
                jsapi.requestVideoQualityChange("0");
            }

            // Attach listener on DataProviderEvent.videoQualityData event. After that qualities list is known
            // and selection is available.
            jsapi.add("DataProviderEvent.videoQualityData", onVideoQualitiesInfo);
        </script>
    </body>
</html>