Playback Using Video Elements

This topic describes how your application can play video content using the HTML5 <video> element.


Related Info


Samples


The HTML5 <video> element is a standard way to embed video content in Web applications. You can use the <video> element to stream video files on a Samsung Smart TV. The <video> element inherits all the properties and methods of the HTMLMediaElement interface.

Samsung TVs support a variety of standard video formats. For more information on the supported formats, see the Media Specifications.

Implementing a Video Player

To create a video player using HTML5:

  1. Create a <video> element, and add attributes and properties.

    You can create the element in HTML or in JavaScript:

    • In HTML:
      <body>
      <video id='video' width='700' height='400' 
        poster='yourPosterURI' src='yourVideoURI' 
        controls style='background:black'>
      </video>
      </body>
      
      The following are some basic attributes for the HTML <video> element. For more information, see the HTML <video> element.
      • autoplay: Start playing the media as soon as it is ready.
      • controls: Show the playback controls.
      • height: Set the height of the video player, in pixels.
      • loop: Start playing the media again from the beginning as soon as it ends.
      • muted: Mute the audio output of the media.
      • poster: Specify an image to show while the media is loading or until the user clicks the play button.
      • preload: Specify whether the application can begin downloading the media or its meta data before the media is needed for playback.
      • src: Set the URI of the media file.
      • width: Set the width of the video player, in pixels.
    • In 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); 
      
      The following are some basic properties for the JavaScript <video> element. You can also use the HTML attributes as properties. For more information, see the HTMLMediaElement Properties.
      • audioTracks: Lists the audio tracks contained in the element.
      • buffered: Returns the time ranges that the video player has buffered.
      • currentTime: Indicates the current playback position, in seconds.
      • duration: Indicates the length of the media, in seconds.
      • ended: Indicates whether the media has finished playing.
      • paused: Indicates whether the media playback is paused.
      • volume: Indicates the audio volume, where 0.0 is silent and 1.0 is loudest.
  2. Define event listeners.

    For more information on the available events, see Media events.

    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.');
    });
    
  3. Control the playback:

    • Use the HTMLMediaElement Methods to control the video player:
      • addTextTrack(): Add a text track, such as subtitles, to the video player.
      • canPlayType(): Determine whether the specified media type can be played.
      • load(): Reset the video player and restart media playback. This method can be useful for releasing resources after any src attribute and <source> element descendants have been removed.
      • pause(): Pause media playback. If playback is already paused, this method has no effect.
      • play(): Begin media playback.
    • To move to a specific time in the media, set the currentTime property. The currentTime property sets or returns the current playback position, in seconds. When you set this property, the playback jumps to the specified position in 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;
      
  • To control the playback rate (trick play) of the media, set the playbackRate property as a multiplier for the playback rate.

    Positive values for the playbackRate property play the media forwards, while negative values cause the media to play in reverse.
    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;
    

Embedding Multiple Video Files

To add multiple videos to a video player, for playing in sequence:

  1. Create a <source> element for each video file you want to add.

    <video id='video' width='700' height='400'>
      <source class='active' src='yourVideoURI_1' ></source>
      <source src='yourVideoURI_2' ></source>
    </video>
    
  2. When the first video has finished playing, start playback for the next video:

    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 the next one
      activeSource.className = '';
      nextSource.className = 'active';
    
      // update the video source and start playback
      videoElement.src = nextSource.src;
      videoElement.play();
    })
    

Adding Captions and Subtitles

You can use the <track> element to add text captions or subtitles to the video. The caption or subtitle track must be in WebVTT (".vtt") format.

  1. In the HTML code, set the attributes for each text <track> element:
    • kind: Type of content the track contains
    • label: Name of the track, to be shown in the video player
    • srclang: Language of the caption or subtitle file contents
    • src: URI to the caption or subtitle file
    • default: Caption or subtitle file to use by default when captioning or subtitling is switched on
      <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>
      
  2. Show the selected track and hide the others:
    var videoElement = document.getElementById('video');
    
    // show English subtitles
    videoElement.textTracks[0].mode = 'showing';
    videoElement.textTracks[1].mode = 'hidden';
    
    // show Deutsch subtitles
    videoElement.textTracks[0].mode = 'hidden';
    videoElement.textTracks[1].mode = 'showing';
    
    
  3. Style the displayed text using CSS.

    WebVTT supports a limited number of CSS properties for text styling, such as color, opacity, and font. For more information, see Adding captions and subtitles to HTML5 video.
    ::cue {
      color:#ccc;
    }
    

Handling Errors

The error property returns an instance of the MediaError interface, which returns a numerical code value representing the error state of the media element.

Value Name Description
1 MEDIA_ERR_ABORTED Fetching process aborted by the user
2 MEDIA_ERR_NETWORK Network error occurred during downloading
3 MEDIA_ERR_DECODE Error occurred during decoding
4 MEDIA_ERR_SRC_NOT_SUPPORTED Media format not supported

Table 1. Media error states

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

videoElement.addEventListener('error', function() {
  /* Video playback failed: show an error message */
  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 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);