轉碼媒體檔案Transcode media files

您可以使用 node.js api, 將影片檔案從一種格式轉碼至另一種格式。You can use the Windows.Media.Transcoding APIs to transcode video files 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. 例如,您可以將 Windows Media 檔案轉換成 MP4,以便在支援 MP4 格式的可攜式裝置上播放。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.

設定您的專案進行轉碼Set up your project for transcoding

除了預設專案範本所參考的命名空間之外,您需要參考這些命名空間,以使用本文中的程式碼轉碼媒體檔案。In addition to the namespaces referenced by the default project template, you will need to reference these namespaces in order to transcode media files using the code in this article.

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

選取來源和目的地檔案Select source and destination files

您的 app 判斷轉碼的來源和目的地檔案的方式取決於您的實作。The way that your app determines the source and destination files for transcoding depends on your implementation. 這個範例使用 FileOpenPickerFileSavePicker 讓使用者挑選來源和目的地檔案。This example uses a FileOpenPicker and a FileSavePicker to allow the user to pick a source and a destination file.

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

建立媒體編碼設定檔Create a media 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.

MediaEncodingProfile 類別提供用來建立預先定義的編碼設定檔的靜態方法:The MediaEncodingProfile class provides static methods for creating predefined encoding profiles:

用於建立僅限音訊編碼設定檔的方法Methods for creating Audio-only encoding profiles

方法Method 設定檔Profile
CreateAlacCreateAlac Apple 無失真音訊轉碼器 (ALAC) 音訊Apple Lossless Audio Codec (ALAC) audio
CreateFlacCreateFlac 免費無失真音訊轉碼器 (FLAC) 音訊。Free Lossless Audio Codec (FLAC) audio.
CreateM4aCreateM4a AAC 音訊 (M4A)AAC audio (M4A)
CreateMp3CreateMp3 MP3 音訊MP3 audio
CreateWavCreateWav WAV 音訊WAV audio
CreateWmvCreateWmv Windows Media 音訊 (WMA)Windows Media Audio (WMA)

用於建立音訊/視訊編碼設定檔的方法Methods for creating audio / video encoding profiles

方法Method 設定檔Profile
CreateAviCreateAvi AVIAVI
CreateHevcCreateHevc 高效率視訊編碼 (HEVC) 視訊,也稱為 H.265 視訊High Efficiency Video Coding (HEVC) video, also known as H.265 video
CreateMp4CreateMp4 MP4 視訊 (H.264 視訊加 AAC 音訊)MP4 video (H.264 video plus AAC audio)
CreateWmvCreateWmv Windows Media 視訊 (WMV)Windows Media Video (WMV)

下列程式碼會建立 MP4 視訊的設定檔。The following code creates a profile for MP4 video.

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

靜態 CreateMp4 方法會建立 MP4 編碼設定檔。The static CreateMp4 method creates an MP4 encoding profile. 這個方法的參數會提供影片的目標解析度。The parameter for this method gives the target resolution for the video. 在這種情況下,VideoEncodingQuality.hd720p 表示 1280 x 720 個像素,每秒 30 個畫面。In this case, VideoEncodingQuality.hd720p means 1280 x 720 pixels at 30 frames per second. (「720p」表示每一個畫面有 720 條漸進式掃描線。) 預先定義設定檔的其他方法都是沿用這個模式。("720p" stands for 720 progressive scan lines per frame.) The other methods for creating predefined profiles all follow this pattern.

另一種方法是,您可以使用 MediaEncodingProfile.CreateFromFileAsync 方法來建立一個符合現有媒體檔案的設定檔。Alternatively, you can create a profile that matches an existing media file by using the MediaEncodingProfile.CreateFromFileAsync method. 或者,如果您知道自己需要的正確編碼設定,可以建立新的 MediaEncodingProfile 物件,並填入設定檔詳細資料。Or, if you know the exact encoding settings that you want, you can create a new MediaEncodingProfile object and fill in the profile details.

檔案轉碼Transcode the file

若要進行檔案的轉碼,請建立新的 MediaTranscoder 物件並呼叫 MediaTranscoder.PrepareFileTranscodeAsync 方法。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. 再呼叫 PrepareTranscodeResult 物件上的 TranscodeAsync 方法,該物件是從非同步轉碼作業傳回的物件。Then call the TranscodeAsync method on the PrepareTranscodeResult object that was returned from the async transcode operation.

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

回應轉碼進度Respond to transcoding progress

您可以註冊事件在非同步進度 TranscodeAsync 的進度變更時回應。You can register events to respond when the progress of the asynchronous TranscodeAsync changes. 這些事件屬於通用 Windows 平台 (UWP) app 的非同步程式設計架構,而不是只屬於轉碼 API。These events are part of the async programming framework for Universal Windows Platform (UWP) apps and are not specific to the transcoding 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.
    }
}