You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 3 Current »

This tutorial shows you how to use the "getTextTracks" and "setTextTrack" functions to automatically enable a subtitle track on load.

Please note that the following functions can be performed only after you have successfully undertaken the first steps (see the "Getting started" chapter). You will also need to replace the video and player IDs with your own.

<!DOCTYPE html>
<html>
<head>
</head>
<body>

<div id="player_container"></div>

<script type="text/javascript">

	//select subtitle track from available tracks
	function getEnSubTrackId(textTracks) {
    	for(var i = 0; i < textTracks.length; i++)
        {
            var track = textTracks[i];
            if(track['language'] == 'en')
            {
                return track['id'];
            }
        }
        return "";
    }
    
    //create a new player instance (vmpro)
	function createPlayer() {
		var initPlayer = {
			success: function (playerApi) {
				var enTrack = getEnSubTrackId(playerApi.getTextTracks());
            	playerApi.setTextTrack(enTrack);
			},
			parameters: {
				configType: 'vmpro',
				playerId: '<PlayerID>',
				videoId: '<VideoID>',
				apiUrl: '//d.video-cdn.net/play',
				flashPath: '//e.video-cdn.net/v2/'
			}
		};

		VideoPlayer.Collection.addPlayerById('player_container', initPlayer);
	}

	//add the player
	var head = document.getElementsByTagName('head')[0];
	var script = document.createElement('script');
	script.type = 'text/javascript';
	script.src = '//e.video-cdn.net/v2/embed.js';
	head.appendChild(script);
	
	script.onload = (function () {
		createPlayer();
	});

</script>

</body>
</html>


The example above gets a list of track objects (using the API's "getTextTracks" function on line 28) and passes it into a new function, "getEnSubTrackId" (defined starting on line 12). This function finds the preferred subtitle track in the available tracks and either outputs its ID, or outputs an empty string if it can't find it. This example looks for the English subtitles track but there are many ways a preferred track can be selected; adjust the function to fit your needs. With the preferred track ID, the "setTextTrack" function is called (on line 29) to automatically enable these subtitles. Now when the video plays, the selected subtitles will play with the video.