Compartilhar via


Quickstart: transcoding video files (XAML)

[ 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 ]

You can use the Windows.Media.Transcoding API to transcode a video files from one format to another. This QuickStart transcode a video file to the MP4 format.

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 quickstart uses the FileOpenPicker class to open a video file from the system. Then it uses the MediaTranscoder class to transcode the video file. Finally, it uses the FileSavePicker class to save the newly encoded file.

A code sample that shows the complete sequence of calls needed for the transcode operation is included at the end of this tutorial. The code examples in this tutorial are extracted from that sample.

For another example of transcoding in a Windows Runtime app using C++, C#, or Visual Basic, see the Transcoding media sample.

Prerequisites

This topic assumes that you can create a basic Windows Runtime app using C++, C#, or Visual Basic . For help creating your first app, see Create your first Windows Store app using C# or Visual Basic.

Instructions

1. Create new project

Start by creating a blank project in Microsoft Visual Studio.

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 that this method calls a method called TrimFile. This is a user-defined method that performs the transcode operation. We will create this method in the next step.

Windows Phone Store app must use pickSingleFileAndContinue.

async void TranscodeVideoFile()
{
    Windows.Storage.StorageFile source;
    Windows.Storage.StorageFile destination;

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

    openPicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.VideosLibrary;
    openPicker.FileTypeFilter.Add(".wmv");
    openPicker.FileTypeFilter.Add(".mp4");

    source = await openPicker.PickSingleFileAsync();

    var savePicker = new Windows.Storage.Pickers.FileSavePicker();

    savePicker.SuggestedStartLocation =
        Windows.Storage.Pickers.PickerLocationId.VideosLibrary;

    savePicker.DefaultFileExtension = ".mp4";
    savePicker.SuggestedFileName = "New Video";

    savePicker.FileTypeChoices.Add("MPEG4", new string[] { ".mp4" });

    destination = await savePicker.PickSaveFileAsync();

    // Method to perform the transcoding.
    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 MediaEncodingProfile class provides methods for creating 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.

MediaEncodingProfile profile =
    MediaEncodingProfile.CreateMp4(VideoEncodingQuality.HD720p);

MediaTranscoder transcoder = new MediaTranscoder();

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 MediaEncodingProfile.CreateFromFileAsync method. Or, if you know the exact encoding settings that you want, you can create a new 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 method on the PrepareTranscodeResult object that was returned from the async transcode operation. You can also create methods to handle error, progress, and completion of async operation.

Be aware that the methods in this sample code call a user-defined method called OutputText. This is a helper method to output message to the user interface (UI).

async void TranscodeFile(StorageFile srcFile, StorageFile destFile)
{
    MediaEncodingProfile profile =
        MediaEncodingProfile.CreateMp4(VideoEncodingQuality.HD720p);

    MediaTranscoder transcoder = new MediaTranscoder();

    PrepareTranscodeResult prepareOp = await
        transcoder.PrepareFileTranscodeAsync(srcFile, destFile, profile);

    if (prepareOp.CanTranscode)
    {
        var transcodeOp = prepareOp.TranscodeAsync();
        transcodeOp.Progress +=
            new AsyncActionProgressHandler<double>(TranscodeProgress);
        transcodeOp.Completed +=
            new AsyncActionWithProgressCompletedHandler<double>(TranscodeComplete);
    }
    else
    {
        switch (prepareOp.FailureReason)
        {
            case TranscodeFailureReason.CodecNotFound:
                OutputText("Codec not found.");
                break;
            case TranscodeFailureReason.InvalidProfile:
                OutputText("Invalid profile.");
                break;
            default:
                OutputText("Unknown failure.");
                break;
        }
    }
}

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. The OutputText method outputs messages to a TextBlock object. The progress update method writes directly to a TextBlock name txtProrgess. The XAML for both of these objects is defined below.

void TranscodeProgress(IAsyncActionWithProgress<double> asyncInfo, double percent)
{
    // Display or handle progress info.
}

void TranscodeComplete(IAsyncActionWithProgress<double> asyncInfo, AsyncStatus status)
{
    asyncInfo.GetResults();
    if (asyncInfo.Status == AsyncStatus.Completed)
    {
        // Display or handle complete info.
    }
    else if (asyncInfo.Status == AsyncStatus.Canceled)
    {
        // Display or handle cancel info.
    }
    else
    {
        // Display or handle error info.
    }
}

Summary

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

First, the code to open and save the file.

async void TranscodeVideoFile()
{
    Windows.Storage.StorageFile source;
    Windows.Storage.StorageFile destination;

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

    openPicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.VideosLibrary;
    openPicker.FileTypeFilter.Add(".wmv");
    openPicker.FileTypeFilter.Add(".mp4");

    source = await openPicker.PickSingleFileAsync();

    var savePicker = new Windows.Storage.Pickers.FileSavePicker();

    savePicker.SuggestedStartLocation =
        Windows.Storage.Pickers.PickerLocationId.VideosLibrary;

    savePicker.DefaultFileExtension = ".mp4";
    savePicker.SuggestedFileName = "New Video";

    savePicker.FileTypeChoices.Add("MPEG4", new string[] { ".mp4" });

    destination = await savePicker.PickSaveFileAsync();

    // Method to perform the transcoding.
    TranscodeFile(source, destination);
}

Next the code to transcode the file.

async void TranscodeFile(StorageFile srcFile, StorageFile destFile)
{
    MediaEncodingProfile profile =
        MediaEncodingProfile.CreateMp4(VideoEncodingQuality.HD720p);

    MediaTranscoder transcoder = new MediaTranscoder();

    PrepareTranscodeResult prepareOp = await
        transcoder.PrepareFileTranscodeAsync(srcFile, destFile, profile);

    if (prepareOp.CanTranscode)
    {
        var transcodeOp = prepareOp.TranscodeAsync();
        transcodeOp.Progress +=
            new AsyncActionProgressHandler<double>(TranscodeProgress);
        transcodeOp.Completed +=
            new AsyncActionWithProgressCompletedHandler<double>(TranscodeComplete);
    }
    else
    {
        switch (prepareOp.FailureReason)
        {
            case TranscodeFailureReason.CodecNotFound:
                OutputText("Codec not found.");
                break;
            case TranscodeFailureReason.InvalidProfile:
                OutputText("Invalid profile.");
                break;
            default:
                OutputText("Unknown failure.");
                break;
        }
    }
}

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

void TranscodeProgress(IAsyncActionWithProgress<double> asyncInfo, double percent)
{
    // Display or handle progress info.
}

void TranscodeComplete(IAsyncActionWithProgress<double> asyncInfo, AsyncStatus status)
{
    asyncInfo.GetResults();
    if (asyncInfo.Status == AsyncStatus.Completed)
    {
        // Display or handle complete info.
    }
    else if (asyncInfo.Status == AsyncStatus.Canceled)
    {
        // Display or handle cancel info.
    }
    else
    {
        // Display or handle error info.
    }
}

Finally, the UI objects for displaying progress and status messages.

    <StackPanel Background="{StaticResource ApplicationPageBackgroundBrush}">
        <TextBlock Name="txtDisplay" Text="Display"></TextBlock>
        <TextBlock Name="txtProgress" Text="Progress"></TextBlock>
    </StackPanel>

Roadmaps

Roadmap for Windows Runtime apps using C# and Visual Basic

Roadmap for Windows Runtime apps using C++

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

Optimize media resources