本記事は書籍「基礎から学ぶWindowsストアアプリ開発」のフォローアップ記事です。
書籍のCHAPTER6で動画を撮影する方法を紹介しましたが、その際は撮影にCameraCaptureUIクラスを利用しました。
CameraCaptureUIクラスを利用する場合、全画面でカメラ撮影モードに入るのですが、今回はストアアプリの画面のままで動画を撮影する方法を紹介します。
ストアアプリの画面にカメラのプレビュー映像を表示したい場合はCaptureElementクラスを利用します。
CaptureElementを利用するには以下のようにXAMLに記載します。
<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
<CaptureElement x:Name="captureElement" HorizontalAlignment="Left" Height="370" Margin="163,133,0,0" VerticalAlignment="Top" Width="599"/>
<Button Content="撮影開始" HorizontalAlignment="Left" Margin="193,537,0,0" VerticalAlignment="Top" Click="Button_Click"/>
<Button Content="撮影終了" HorizontalAlignment="Left" Margin="304,537,0,0" VerticalAlignment="Top" Click="Button_Click_1"/>
</Grid>
続いてC#のコードビハインドに以下のように記述します。
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
var mediaCapture = new Windows.Media.Capture.MediaCapture();
await mediaCapture.InitializeAsync();
this.captureElement.Source = mediaCapture;
await mediaCapture.StartPreviewAsync();
}
Package.appxmanifestの機能タブでカメラとマイクにチェックを入れます。この後必要になるのでビデオライブラリにもチェックを入れておきます。
これでCaptureElementコントロールにカメラプレビューが表示されました。
C#のコードビハインドに以下の2つのメソッドを追加します。
private MediaCapture capture;
private async void Button_Click(object sender, RoutedEventArgs e)
{
capture = this.captureElement.Source;
MediaEncodingProfile encordingProfile = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Vga);
StorageFile file = await Windows.Storage.KnownFolders.VideosLibrary.CreateFileAsync("samplevideo.mp4", CreationCollisionOption.GenerateUniqueName);
await capture.StartRecordToStorageFileAsync(encordingProfile, file);
}
private async void Button_Click_1(object sender, RoutedEventArgs e)
{
//this.captureElement.Source = null;
await capture.StopRecordAsync();
}
これで撮影開始で撮影を開始し、撮影終了で撮影を終了して動画を保存することができます。
これまでのフォローアップは [書籍]基礎から学ぶ Windowsストアアプリ開発フォローアップを参照ください。
Please give us your valuable comment