Skip to content
This repository has been archived by the owner on Jul 19, 2024. It is now read-only.

Changing the Media

Scott Miller edited this page Mar 17, 2016 · 2 revisions

This topic provides an example of how to alter the media tag associated with a MediaPlayer control after the MediaPlayer control has been created and is potentially playing. The example provided in this topic deals specifically with videos, but you can use the same concepts for audio tags as well. This can be done whether you create your MediaPlayer control declaratively or through code.

This code can be added to your HTML file. It creates the MediaPlayer and automatically begins playing the associated video.

<body>
<div id="myMediaPlayer">
<video id="myVideo" autoplay="autoplay" src="http://smf.blob.core.windows.net/samples/videos/bigbuck.mp4">
</video>
</div>
</body>

The following section of code can be added to your JavaScript file. It is a handler function for when a user presses the custom button. This handler function changes the video stream to a second source, and it updates the metadata associated with the video.

JavaScript

function changeSourceButtonClick() {  
    // This creates the new video tag
    var videoTag = document.createElement("video");
    videoTag.src="http://smf.blob.core.windows.net/samples/videos/wildlife.mp4";
   
    // This retrieves the MediaPlayer  
    var mediaPlayer = document.getElementById("myMediaPlayer").tvControl;
  
    // This changes the video associated with the MediaPlayer
    mediaPlayer.mediaElementAdapter.mediaElement = videoTag;
  
    // We also need to create new metadata for the contentID
    var metadata = {
        title: "Wildlife Video",
        description: "A brief clip of wildlife footage.",
        contentId: "123456789"
    }
  
    // Set the metadata
    mediaPlayer.setContentMetadata(metadata);
}  

The following code adds a custom button and associates it with the handler defined earlier.

JavaScript

// Get the MediaPlayer. In this example the MediaPlayer is named myMediaPlayer.
var mediaPlayer = document.getElementById("myMediaPlayer").tvControl;
  
// Create the new button
var changeSourceButton = document.createElement("button");
  
// Create the icon and voice attributes
// This example uses the replay provided icon. You can either use one of 
// the icons provided or create your own.  
var icon = document.createElement("span");
icon.classList.add("tv-mediaplayer-icon tv-mediaplayer-replayicon");
  
changeSourceButton.appendChild(icon);
  
  
// Get one of the buttons on the transport bar
var transportBarButton = mediaPlayer.element.querySelector(".tv-mediaplayer-displaymodebutton");

// Add this button as a new child - this will add it after the last button
transportBarButton.parentNode.appendChild(changeSourceButton);

// Hook up the response method
changeSourceButton.addEventListener("click", changeSourceButtonClick, false);