top

Using video Element

This document covers how to play media contents by using video element.

Overview

Samsung TV supports the video HTML5 media element. The video element specifies standard way to embed video content in application. You can use the video element to play video files streaming, without separate plug-in.

To get the most out of video element, you should first

  • learn to create the video element

  • learn how to use / control that using JavaScript

  • learn to apply CSS styles to video element and modify styles dynamically using JavaScript.

Using JavaScript, the playback can be controlled with Media Events (W3C). The video element used as media elements inherit all the properties and methods of the Media Elements interface.

Samsung TV supports the video formats based upon a standard specs.
For more information, go to Supported Media Formats.

Creating Video Player

The video element expose methods, properties, and events to JavaScript. There are methods for playing, pausing, and changing the video source URL dynamically.

Creating HTML5 Video Element

Choose one of the two below as you want.

  • HTML

    <body>
    	<video id='video'></video>
    </body>
    
  • JavaScript

    var videoElement = document.createElement('video');
    document.body.appendChild(videoElement);
    

Adding Attributes and Properties

The HTML representation of a DOM element has attribute. But when represented as a JavaScript object those attributes appear as object property.

To create a video player, add necessary attributes/properties to video element.

  • Attributes for video element
    The video element supports a number of attributes to control video playback and display. This table highlights the basic video attributes. For more information, go to Attributes

    Table 1. Attributes for video element
    Attribute Description
    autoplay Specifies that the video will start playing as soon as it is ready
    controls Specifies that video controls should be displayed (such as a play/pause button etc)
    height Sets the height of the video player in pixels
    loop Specifies that the video will start over again, every time it is finished
    muted Specifies that the audio output of the video should be muted
    poster Specifies an image to be shown while the video is downloading, or until the user hits the play button
    preload Specifies if and how the author thinks the video should be loaded when the page loads
    src A string that represents a URL that points to a video file
    width Sets the width of the video player in pixels
  • Properties for video element
    The video element supports a number of properties to control video playback and display. This table highlights the basic video properties. For more information, go to Properties

    Table 2. Properties for video element
    Property Description
    audioTracks A AudioTrackList that lists the AudioTrack objects contained in the element
    buffered Returns a TimeRanges object that indicates the ranges of the media source that the browser has buffered (if any) at the moment the buffered property is accessed
    currentTime Is a double indicating the current playback time in seconds. Setting this value seeks the media to the new time
    duration Returns a double indicating the length of the media in seconds, or 0 if no media data is available
    ended Returns a Boolean that indicates whether the media element has finished playing
    paused Returns a Boolean that indicates whether the media element is paused
    volume Is a double indicating the audio volume, from 0.0 (silent) to 1.0 (loudest)

Choose one of the two below as you want.

  • HTML

    <body>
    	<video id='video' width='700' height='400'
    		poster='yourPosterURI' src='yourVideoURI'
    		controls style='background:black'>
    	</video>
    </body>
    
  • JavaScript

    var videoElement = document.createElement('video');
    
    videoElement.id = 'video';
    videoElement.width = '700';
    videoElement.height = '400';
    videoElement.poster = 'yourPosterURI';
    videoElement.src = 'yourVideoURI' ;
    videoElement.controls = true;
    videoElement.style.background='black';
    videoElement.load();
    
    document.body.appendChild(videoElement);
    
Note

The preload attribute/property is set to auto by default, meaning that the video metadata is automatically loaded. If you do not want to load the metadata, set the attribute value as metadata or none.

Important

We recommend that the background color is black.

Attaching Event Listener

Various events are sent when handling video that are embedded in HTML documents using the video element.
For more information, go to Media Events (MDN)

var videoElement = document.getElementById('video');

videoElement.addEventListener('loadeddata', function() {
	console.log('Video loaded.');
});

videoElement.addEventListener('timeupdate', function() {
	console.log('Current time: ' + videoElement.currentTime);
});

videoElement.addEventListener('seeked', function() {
	console.log('Seek operation completed.');
	videoElement.play();
});

videoElement.addEventListener('stalled', function() {
	console.log('Video stalled.');
});

videoElement.addEventListener('ended', function() {
	console.log('Video ended.');
});

Using Method

The methods of video element are used to control video player. The following table highlights the basic video methods.
For more information, go to Media Methods

Table 3. Methods of video element
Method Description
addTextTrack Adds a text track (such as a track for subtitles) to a media element.
load This method can be useful for releasing resources after any src attribute and source element descendants have been removed.
play Begins playback of the media.
pause Pauses the media playback.
canPlayType Determines whether the specified media type can be played back.
  • play
    play() method attempts to begin playback of the video.

    var videoElement = document.getElementById('video');
    videoElement.play();
    
  • pause
    pause() method will pause playback of the video, if the video is already in a paused state this method will have no effect.

    var videoElement = document.getElementById('video');
    videoElement.pause();
    
  • canPlayType
    The canPlayType() method determines whether the specified media type can be played back.

    The return values are :

    • ‘probably’ : The specified media type appears to be playable.
    • ‘maybe’ : Cannot tell if the media type is playable without playing it.
    • ’ '(empty string) : The specified media type definitely cannot be played.


    For more information, go to canPlayType.

    var videoElement = document.getElementById('video');
    console.log(videoElement.canPlayType('video/webm')); // 'probably'
    console.log(videoElement.canPlayType('video/mp4')); // 'maybe'
    

Controlling Playback

Seeking Media Time

The currentTime property of video element sets or returns the current position (in seconds) of the video playback. When setting this property, the playback will jump to the specified position. Property value is seconds which indicates the position for the playback of the video.

var videoElement = document.getElementById('video');

/* Move 10 seconds forward */
var seekTime = videoElement.currentTime + 10;
if( seekTime >= 0 && seekTime <= videoElement.duration ) {
	videoElement.currentTime = seekTime;
}

/* Move 10 seconds back */
var seekTime = videoElement.currentTime - 10;
if( seekTime >= 0 && seekTime <= videoElement.duration ) {
	videoElement.currentTime = seekTime;
}

/* Move currentTime to 30 seconds */
videoElement.currentTime = 30;
Important

  • If the metadata of the video file is loaded, you can move to the assigned timeline position even when the video file is not playing.
  • For more information, see Retrieving Media Information.

Trick Play Video

The playbackRate property of video element sets or returns the current playback speed of the video. Property value is playbackspeed which indicates the current playback speed of the video. For example,

Table 4. Playback Speed of the Video
Value Description
1.0 It means normal speed.
0.5 It means half speed (slower).
2.0 It means double speed (faster).
-1.0 It means backwards, normal speed.
-0.5 It means backwards, half speed.
var videoElement = document.getElementById('video');

/* Set to half speed */
var speed = 0.5;
videoElement.playbackRate = speed;

/* Set to double speed */
var speed = 2.0;
videoElement.playbackRate = speed;

Multiple Videos

The src attribute/property contains a path to the video you want to embed. And this one is available as source element. If there are multiple videos, you can use multiple source element.

  • HTML

    <video id='video' width='700' height='400'>
    	<source class='active' src='yourVideoURI_1' ></source>
    	<source src='yourVideoURI_2' ></source>
    </video>
    
    Note

    Each source element also has a type attribute. This is optional, but it is advised that you include them — they contain the MIME types of the video files, and browsers can read these and immediately skip videos they don’t understand.

  • JavaScript

    var videoElement = document.getElementById('video');
    
    videoElement.addEventListener('ended', function(e){
    	var activeSource = document.querySelector('#video source.active');
    	var nextSource = document.querySelector('#video source.active + source') || document.querySelector('#video source:first-child');
    
    	// deactivate current source, and activate next one
    	activeSource.className = '';
    	nextSource.className = 'active';
    
    	// update the video source and play
    	videoElement.src = nextSource.src;
    	videoElement.play();
    })
    

Adding Captions and Subtitles to Video

Before diving into how to add captions to the video player, there are a number of things that we will first mention, which you should be aware of before we start.

  • Captions versus subtitles
    Captions and subtitles are not the same thing : they have significantly different audiences, and convey different information, and it is recommended that you read up on the differences if you are not sure what they are. They are however implemented in the same way technically, so the material in this article will apply to both.
  • The track element
    The various attributes of this element allow us to specify such things as the type of content that we’re adding, the language it’s in, and of course a reference to the text file that contains the actual subtitle information.

We provide a few reference code.

  • HTML

    <video id='video'>
    	<source src='yourVideoURI' type='yourVideoType' ></source>
    	<track label='English' kind='subtitles' srclang='en' src='yourSubtitleURI_en' default></track>
    	<track label='Deutsch' kind='subtitles' srclang='de' src='yourSubtitleURI_de'></track>
    </video>
    
    Important

    The format of the track file must be .vtt, and must be a valid URL.

  • JavaScript

    var videoElement = document.getElementById('video');
    
    // show english subtitle.
    videoElement.textTracks[0].mode = 'showing';
    videoElement.textTracks[1].mode = 'hidden';
    
    // show Deutsch subtitle.
    videoElement.textTracks[0].mode = 'hidden';
    videoElement.textTracks[1].mode = 'showing';
    
  • CSS

    ::cue {
    	color:#ccc;
    }
    
    Note

    The cue pseudo-element is the key to targetting individual text track cues for styling, as it matches any defined cue. There are only a handful of CSS properties that can be applied to a text cue : color / opacity / font / and so on.
    For more information, go to Styling the displayed subtitles

Handling Errors

The error property returns MediaError object. The MediaError object has a code property containing the error state of the video element. Return type is Number. For example,

Table 5. Error State of the Video
Return Value Description
1 MEDIA_ERR_ABORTED, fetching process aborted by user.
2 MEDIA_ERR_NETWORK, error occurred when downloading.
3 MEDIA_ERR_DECODE, error occurred when decoding.
4 MEDIA_ERR_SRC_NOT_SUPPORTED, video not supported.
var videoElement = document.getElementById('video');

videoElement.addEventListener('error', function() {
	/* Video playback failed: show a message saying why */
	switch(videoElement.error.code)	{
		case 1:
		// 'MEDIA_ERR_ABORTED : 1, Media data download is stopped by the user'
		break;

		case 2:
		// 'MEDIA_ERR_NETWORK : 2, Download is stopped due to network error'
		break;

		case 3:
		// 'MEDIA_ERR_DECODE : 3, Media data decoding failure'
		break;

		case 4:
		// 'MEDIA_ERR_SRC_NOT_SUPPORTED : 4, Format not supported'
		break;
	}
}, false);

Sample Applications