single.php

C# WinUI3でWMV形式をMP4に変換する方法[MediaTranscoder]

C# WinUI 3アプリを作っていく途中で、調べたことを忘録的に投稿します。今回はWinUI3プロジェクトで[Windows Media Video オーディオ (WMV)]形式を[MP4]形式に変換する手順です。

[MediaTranscoder]クラス

C#で扱える、映像や音声などのメディアの変換を行う[MediaTranscoder]クラスを利用して[Windows Media Video オーディオ (WMV)]形式を[MP4]などに変換ができます。

また[MediaTranscoder]クラスは[AAC オーディオ (M4A)]や[MP3 オーディオ]、[Windows Media Audio (WMA)]など音声形式を、別形式に変換が可能です。

今回は、サンプルとして[Windows Media Video (WMV)]形式のファイルを[MP4 ビデオ]形式に変換しています。

変換元や変換先のファイルパスを指定する画面を用意します。

<Grid HorizontalAlignment="Stretch" VerticalAlignment="Center">
    <Grid.RowDefinitions>
        <RowDefinition Height = "64"/>
        <RowDefinition Height = "64"/>
        <RowDefinition Height = "Auto"/>
    </Grid.RowDefinitions>
    <StackPanel Grid.Row="0" Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Center">
        <TextBlock Name="sourcefile_path" Text="Source Media File Path..." Margin="0,4,12,0"/>
        <Button Name="sourcefile_browse" Click="sourcefile_browse_Click">Browse</Button>
    </StackPanel>
    <StackPanel Grid.Row="1" Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Center">
        <TextBlock Name="transcodefile_path" Text="Transcode Media File Path..." Margin="0,4,12,0"/>
        <Button Name="transcodefile_browse" Click="transcodefile_browse_Click">Browse</Button>
    </StackPanel>
    <StackPanel Grid.Row="2" Orientation="Vertical" HorizontalAlignment="Center" VerticalAlignment="Center">
        <Button Name="transcodefile_button" Click="transcodefile_Click">Transcode</Button>
        <TextBlock Name="transcode_status"/>
    </StackPanel>
</Grid>

追加したボタンのイベントプロシージャにコードを追加します。

private async void sourcefile_browse_Click(object sender, RoutedEventArgs e)
{
  //変換元のファイル場所を選択
  IntPtr hWnd = WinRT.Interop.WindowNative.GetWindowHandle(this);
  FileOpenPicker picker = new Windows.Storage.Pickers.FileOpenPicker();
  InitializeWithWindow.Initialize(picker, hWnd);
  picker.FileTypeFilter.Add(".wmv");
  StorageFile sourcefile = await picker.PickSingleFileAsync();
  if (sourcefile != null)
  {
    sourcefile_path.Text = sourcefile.Path;
  }
}

private async void transcodefile_browse_Click(object sender, RoutedEventArgs e)
{
  //変換先ファイル場所を選択
  IntPtr hWnd = WinRT.Interop.WindowNative.GetWindowHandle(this);
  FileSavePicker picker = new Windows.Storage.Pickers.FileSavePicker();
  InitializeWithWindow.Initialize(picker, hWnd);
  picker.DefaultFileExtension = ".mp4";
  picker.SuggestedFileName = "Convert Audio";
  picker.FileTypeChoices.Add("H.264 Video", new string[] { ".mp4" });
  StorageFile transcodefile = await picker.PickSaveFileAsync();
  if (transcodefile != null)
  {
    transcodefile_path.Text = transcodefile.Path;
  }
}

private async void transcodefile_Click(object sender, RoutedEventArgs e)
{
  transcodefile_button.IsEnabled = false;

  //変換処理
  MediaEncodingProfile profile = MediaEncodingProfile.CreateMp4(AudioEncodingQuality.High);

  MediaTranscoder transcoder = new MediaTranscoder();
  StorageFile sourcefile = await StorageFile.GetFileFromPathAsync(sourcefile_path.Text);
  StorageFile transcodefile = await StorageFile.GetFileFromPathAsync(transcodefile_path.Text);

  PrepareTranscodeResult prepareTranscodeResult = await transcoder.PrepareFileTranscodeAsync(sourcefile, transcodefile, profile);
  if (prepareTranscodeResult.CanTranscode)
  {
    var transcodeResult = prepareTranscodeResult.TranscodeAsync();
    //変換終了のイベントを登録
    transcodeResult.Completed += new AsyncActionWithProgressCompletedHandler<double>(TranscodeComplete);
  }
}

void TranscodeComplete(IAsyncActionWithProgress<double> asyncInfo, AsyncStatus status)
{
  //変換終了のイベント
  asyncInfo.GetResults();
  if (asyncInfo.Status == AsyncStatus.Completed)
  {
     this.DispatcherQueue.TryEnqueue(Microsoft.UI.Dispatching.DispatcherQueuePriority.Normal, () => UpdateTranscodeControl(1));
  }
  else if (asyncInfo.Status == AsyncStatus.Canceled)
  {
     this.DispatcherQueue.TryEnqueue(Microsoft.UI.Dispatching.DispatcherQueuePriority.Normal, () => UpdateTranscodeControl(0));
  }
  else
  {
     this.DispatcherQueue.TryEnqueue(Microsoft.UI.Dispatching.DispatcherQueuePriority.Normal, () => UpdateTranscodeControl(-1));
  }
}

private void UpdateTranscodeControl(int status)
{
  //Xamlに配置したコントロールの更新
  switch(status)
  {
    case 1:
      sourcefile_path.Text = "Source Media File Path...";
      transcodefile_path.Text = "Transcode Media File Path...";
      transcodefile_button.IsEnabled = true;
      transcode_status.Text = "TransCode Complete";
      break;

    case 0:
      transcodefile_button.IsEnabled = true;
      transcode_status.Text = "TransCode Canceled";
      break;
    default:
      transcodefile_button.IsEnabled = true;
      transcode_status.Text = "TransCode Error";
      break;
  }
}

[Transcode]ボタンをクリックすると、指定した[Windows Media Video (WMV)]形式の動画ファイルが[MP4]形式に変換されます。

まとめ

今回は、WinUI3プロジェクトで[Windows Media Video オーディオ (WMV)]形式を[MP4]形式に変換する手順について紹介しました。

C#で扱える、映像や音声などのメディアの変換を行う[MediaTranscoder]クラスが用意されていて[Windows Media Video オーディオ (WMV)]形式を[MP4]などに変換ができます。

また[MediaTranscoder]クラスは[AAC オーディオ (M4A)]や[MP3 オーディオ]、[Windows Media Audio (WMA)]など音声形式を、別形式に変換が可能です。

今回は、サンプルとして[Windows Media Video (WMV)]形式のファイルを[MP4 ビデオ]形式に変換しています。

すべての形式には対応していませんが[MediaEncodingProfile]クラスでインスタンスが作成できる形式であれば、変換処理ができます。

WinUI 3で音声や映像ファイルの形式を変換したい人の参考になれば幸いです。

スポンサーリンク

最後までご覧いただき、ありがとうございます。

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です