Share via


Quickstart: transcoding video files (HTML)

[This article is for Windows 8.x and Windows Phone 8.x developers writing Windows Runtime apps. If you’re developing for Windows 10, see the latest documentation]

The Windows.Media.Transcoding API transcode a video file from one format to another.

Transcoding is the conversion of a digital media file, such as a video or audio file, from one format to another. This is usually done by decoding and then re-encoding the file. For example, you might convert a Windows Media file to MP4 so that it can be played on a portable device that supports MP4 format. Or, you might convert a high-definition video file to a lower resolution. In that case, the re-encoded file might use the same codec as the original file, but it would have a different encoding profile.

This tutorial shows how to transcode a video file to MP4 format. It describes how to use the FileOpenPicker class to open a video file from the system, and then the MediaTranscoder class to transcode the video file to the MP4 format. Finally, it describes how to use the FileSavePicker class to save the newly encoded file.

The full listing of code in this Quickstart is included at the end of this tutorial. Add this code to your Program.js file.

For another example of transcoding in a Windows Runtime app using JavaScript, see the Transcoding media sample.

Prerequisites

This topic assumes that you can create a basic Windows Runtime app using JavaScript. For help creating your first app, see Create your first Windows Store app using JavaScript.

Instructions

1. Create new project

Start by creating a blank Windows Store app using JavaScript. For more information, see Create your first Windows Store app using JavaScript.

2. Select a source file and create a destination file

Use the FileOpenPicker class to select a source file and the FileSavePicker class to create the destination file. Set the SuggestedStartLocation and FileTypeFilter properties on the FileOpenPicker. On the FileSavePicker object, set the SuggestedStartLocation, DefaultFileExtension, SuggestedFileName, and FileTypeChoices properties. Note, this function calls a function called TranscodeFile. This is a user-defined function that performs the transcode operation. We will create this function in the next step.

Windows Phone Store app using JavaScript must use PickSingleFileAndContinue instead of PickSingleFileAsync.

function transcodeVideoFile() {
    var source;
    var destination

    var openPicker = new Windows.Storage.Pickers.FileOpenPicker();

    openPicker.suggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.videosLibrary;
    openPicker.fileTypeFilter.replaceAll([".wmv", ".mp4"]);

    openPicker.pickSingleFileAsync().then(
        function (file) {
            source = file;
            var savePicker = new Windows.Storage.Pickers.FileSavePicker();

            savePicker.suggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.videosLibrary;
            savePicker.defaultFileExtension = ".mp4";
            savePicker.suggestedFileName = "New Video";
            savePicker.fileTypeChoices.insert("MPEG4", [".mp4"]);

            return savePicker.pickSaveFileAsync();
        }).then(
        function (file) {
            destination = file;

            TranscodeFile(source, destination);
        });
};

3. Create an encoding profile

The encoding profile contains the settings that determine how the destination file will be encoded. This is where you have the greatest number of options when you transcode a file.

The Windows.Media.MediaProperties namespace provides a set of predefined encoding profiles:

  • AAC audio (M4A)
  • MP3 audio
  • Windows Media Audio (WMA)
  • MP4 video (H.264 video plus AAC audio)
  • Windows Media Video (WMV)

The first three profiles in this list contain audio only. The other two contain video and audio.

The following code creates a profile for MP4 video.

var profile = Windows.Media.MediaProperties.MediaEncodingProfile.createMp4(
        Windows.Media.MediaProperties.VideoEncodingQuality.hd720p);

The static CreateMp4 method creates an MP4 encoding profile. The parameter for this method gives the target resolution for the video. In this case, VideoEncodingQuality.hd720p means 1280 x 720 pixels at 30 frames per second. ("720p" stands for 720 progressive scan lines per frame.) The other methods for creating predefined profiles all follow this pattern.

Alternatively, you can create a profile that matches an existing media file by using the Windows.Media.MediaProperties.MediaEncodingProfile.CreateFromFileAsync method. Or, if you know the exact encoding settings that you want, you can create a new Windows.Media.MediaProperties.MediaEncodingProfile object and fill in the profile details.

4. Transcode the file

To transcode the file, create a new MediaTranscoder object and call the MediaTranscoder.PrepareFileTranscodeAsync method. Pass in the source file, the destination file, and the encoding profile. Then call the TranscodeAsync function on the PrepareTranscodeResult object that was returned from the async transcode operation. You can also create functions to handle error, progress, and completion of async operation.

/// <param name="srcFile" type="IStorageFile"/>
/// <param name="destFile" type="IStorageFile"/>
function TranscodeFile(srcFile, destFile) {

    var profile = Windows.Media.MediaProperties.MediaEncodingProfile.createMp4(
            Windows.Media.MediaProperties.VideoEncodingQuality.hd720p);

    var transcoder = new Windows.Media.Transcoding.MediaTranscoder();

    transcoder.prepareFileTranscodeAsync(srcFile, destFile, profile).then(function (result) {
        if (result.canTranscode) {
            result.transcodeAsync().then(transcodeComplete, transcoderErrorHandler, transcodeProgress);
        } else {
            // Handle error condition. result.failureReason
        }
    });
};

The PrepareFileTranscodeAsync method is asynchronous. This enables transcoding to occur in the background while the UI stays responsive.

You should also update the UI and handle any errors that occur.

function transcodeComplete(result) {
    // handle completion.

    // This snippet writes to an HTML control which is defined external to this snippet.
    OutputText.innerHTML = "Transcode Complete";
};

function transcoderErrorHandler(error) {
    // handle error condition
};

function transcodeProgress(percent) {

    // handle progress.
    // This snippet writes to an HTML control which is defined external to this snippet.
    ProgressText.innerHTML = "Transcode Progress: " + percent.toString().split(".")[0] + "%";
};

Summary

The following code sample shows the complete sequence of calls for the transcode operation.

First, the code to open and save the file.

function transcodeVideoFile() {
    var source;
    var destination

    var openPicker = new Windows.Storage.Pickers.FileOpenPicker();

    openPicker.suggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.videosLibrary;
    openPicker.fileTypeFilter.replaceAll([".wmv", ".mp4"]);

    openPicker.pickSingleFileAsync().then(
        function (file) {
            source = file;
            var savePicker = new Windows.Storage.Pickers.FileSavePicker();

            savePicker.suggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.videosLibrary;
            savePicker.defaultFileExtension = ".mp4";
            savePicker.suggestedFileName = "New Video";
            savePicker.fileTypeChoices.insert("MPEG4", [".mp4"]);

            return savePicker.pickSaveFileAsync();
        }).then(
        function (file) {
            destination = file;

            TranscodeFile(source, destination);
        });
};

Next the code to transcode the file.

/// <param name="srcFile" type="IStorageFile"/>
/// <param name="destFile" type="IStorageFile"/>
function TranscodeFile(srcFile, destFile) {

    var profile = Windows.Media.MediaProperties.MediaEncodingProfile.createMp4(
            Windows.Media.MediaProperties.VideoEncodingQuality.hd720p);

    var transcoder = new Windows.Media.Transcoding.MediaTranscoder();

    transcoder.prepareFileTranscodeAsync(srcFile, destFile, profile).then(function (result) {
        if (result.canTranscode) {
            result.transcodeAsync().then(transcodeComplete, transcoderErrorHandler, transcodeProgress);
        } else {
            // Handle error condition. result.failureReason
        }
    });
};

Finally, the code to handle the transcode progress, error, and completion.

function transcodeComplete(result) {
    // handle completion.

    // This snippet writes to an HTML control which is defined external to this snippet.
    OutputText.innerHTML = "Transcode Complete";
};

function transcoderErrorHandler(error) {
    // handle error condition
};

function transcodeProgress(percent) {

    // handle progress.
    // This snippet writes to an HTML control which is defined external to this snippet.
    ProgressText.innerHTML = "Transcode Progress: " + percent.toString().split(".")[0] + "%";
};

Roadmaps

Roadmap for Windows Store apps using JavaScript

Designing UX for apps

Adding multimedia

Samples

Transcoding media sample

Media extension sample

Real-Time communication sample

Tasks

How to trim a video file

Reference

Windows.Media

Windows.Media.MediaProperties

Windows.Media.Transcoding

MediaTranscoder

PrepareTranscodeResult

TranscodeAsync

Other resources

Supported audio and video formats

Audio and video performance