轉碼媒體檔案

你可以用Windows。Media.Transcoding API 用於將影片檔案從一種格式轉碼到另一種格式。

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

選擇來源與目標檔案

你的應用程式決定轉碼的來源和目的地檔案的方式,取決於你的實作方式。 此範例使用 FileOpenPicker 與 FileSavePicker 來讓使用者選擇來源檔案與目標檔案。

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

// Initialize the picker with the window handle (required for WinUI desktop apps).
var hwnd = WinRT.Interop.WindowNative.GetWindowHandle(App.MainWindow);
WinRT.Interop.InitializeWithWindow.Initialize(openPicker, hwnd);

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();

WinRT.Interop.InitializeWithWindow.Initialize(savePicker, hwnd);

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類別提供建立預設編碼配置檔的靜態方法:

建立純音頻編碼設定檔的方法

方法 Profile
創造阿拉克 Apple 無損音訊編碼器(ALAC)音訊
CreateFlac 免費無損音訊編碼器(FLAC)音訊
CreateM4a AAC 音訊(M4A)
CreateMp3 MP3 音訊
CreateWav WAV 音訊
CreateWma Windows 媒體音訊(WMA)

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

方法 Profile
CreateAv1 AOMedia Video 1(AV1)影片
CreateAvi AVI
CreateHevc 高效率視訊編碼(HEVC)影片,也稱為 H.265 影片
CreateMp4 MP4 影片(H.264 影片加上 AAC 音訊)
CreateVp9 VP9 影片
CreateWmv Windows Media 影片(WMV)

以下程式碼會建立 MP4 影片的設定檔。

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

靜態 的 CreateMp4 方法會建立 MP4 編碼設定檔。 此方法的參數給出影片的目標解析度。 在此情況下,VideoEncodingQuality.hd720p 表示 1280 x 720 像素,每秒 30 幀。 (「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 應用程式非同步程式框架的一部分,並非專屬於轉碼 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.
    }
}