轉碼媒體檔案

您可使用 Windows.Media.Transcoding API,將視訊檔案從一種格式轉碼成另一種格式。

「轉碼」是從一種格式轉換成另一種格式的數位媒體檔案 (例如視訊或音訊檔案) 轉換。 這通常是透過將檔案解碼後重新編碼來完成。 例如,您可以將 Windows Media 檔案轉換成 MP4,以便在支援 MP4 格式的可攜式裝置上播放。 或者,您可以將高畫質視訊檔案轉換成較低的解析度。 在此情況下,重新編碼的檔案可能會使用與原始檔案相同的轉碼器,但會有不同的編碼設定檔。

設定您的專案以進行轉碼

除了預設專案範本所參考的命名空間之外,您還需要參考這些命名空間,才能使用本文中的程式碼來將媒體檔案轉碼。

using Windows.Storage;
using Windows.Media.MediaProperties;
using Windows.Media.Transcoding;

選取來源和目的地檔案

您的應用程式決定轉碼來源和目的地檔案的方式,取決於您的實作。 此範例會使用 FileOpenPickerFileSavePicker,讓使用者挑選來源和目的地檔案。

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

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

StorageFile 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" });

StorageFile destination = await savePicker.PickSaveFileAsync();

建立媒體編碼設定檔

編碼設定檔包含決定目的地檔案編碼方式的設定。 當您將檔案轉碼時,這是您有最多選項的位置。

MediaEncodingProfile 類別提供靜態方法來建立預先定義的編碼設定檔:

建立僅限音訊編碼設定檔的方法

方法 設定檔
CreateAlac Apple Lossless Audio Codec (ALAC) 音訊
CreateFlac Free Lossless Audio Codec (FLAC) 音訊。
CreateM4a AAC 音訊 (M4A)
CreateMp3 MP3 音訊
CreateWav WAV 音訊
CreateWmv Windows Media Audio (WMA)

建立音訊 / 視訊編碼設定檔的方法

方法 設定檔
CreateAvi AVI
CreateHevc 高效率視訊編碼 (HEVC) 影片,也稱為 H.265 影片
CreateMp4 MP4 視訊 (H.264 視訊加上 AAC 音訊)
CreateWmv Windows Media Video (WMV)

下列程式碼會建立 MP4 視訊的設定檔。

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

靜態 CreateMp4 方法可建立 MP4 編碼設定檔。 這個方法的參數會提供視訊的目標解析度。 在此情況下,VideoEncodingQuality.hd720p 表示每秒 30 個畫面格的 1280 x 720 像素。 ("720p" 代表每畫面格 720 條逐行掃描線。)建立預先定義設定檔的其他方法全都遵循此模式。

或者,您可以使用 MediaEncodingProfile.CreateFromFileAsync 方法來建立符合現有媒體檔案的設定檔。 或者,如果您知道所要的確切編碼設定,您可建立新的 MediaEncodingProfile 物件並填入設定檔詳細資料。

檔案轉碼

若要將檔案轉碼,請建立新的 MediaTranscoder 物件,並呼叫 MediaTranscoder.PrepareFileTranscodeAsync 方法。 傳入來源檔案、目的地檔案和編碼設定檔。 然後在從非同步轉碼作業傳回的 PrepareTranscodeResult 物件上呼叫 TranscodeAsync 方法。

MediaTranscoder transcoder = new MediaTranscoder();

PrepareTranscodeResult prepareOp = await
    transcoder.PrepareFileTranscodeAsync(source, destination, 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:
            System.Diagnostics.Debug.WriteLine("Codec not found.");
            break;
        case TranscodeFailureReason.InvalidProfile:
            System.Diagnostics.Debug.WriteLine("Invalid profile.");
            break;
        default:
            System.Diagnostics.Debug.WriteLine("Unknown failure.");
            break;
    }
}

回應轉碼進度

您可以註冊事件,以在非同步 TranscodeAsync 的進度變更時回應。 這些事件是通用 Windows 平台 (UWP) 應用程式的非同步程式設計架構的一部分,並非轉碼 API 特有。

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.
    }
}