ユニバーサルWindowsアプリ(Pre)入門012:カメラ操作1

木曜日 , 25, 6月 2015 Leave a comment

 毎度のお約束、本記事はプレビュー状態のOS、IDE、SDKを利用しております。製品版では異なる可能性があります。

 

 本記事はWindows 10向けのユニバーサルWindowsアプリについて学んだことを残して行く記事です。

 これまでの記事はカテゴリ「UWP(Win 10) Preview」を参照ください。

 

カメラ操作

 

 今回はユニバーサルWindowsアプリのサンプルからCameraStarterKitを眺めてみることにします。

 Windows Phoneは当然カメラがありますが、ストアアプリだと端末依存なので、この辺の分岐処理が必要になりそうです。

 

カメラがあるか確認

 

 こういうデバイスが利用可能かの確認はユニバーサルWindowsアプリ(Pre)入門006:デバイスが機能に対応しているか調べるで紹介したように、ApiInformation.IsTypePresentメソッドを利用するんでしたよね。

 

// Get available devices for capturing pictures
var allVideoDevices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);

// Get the desired camera by panel
DeviceInformation desiredDevice = allVideoDevices.FirstOrDefault(x => x.EnclosureLocation != null && x.EnclosureLocation.Panel == desiredPanel);

// If there is no device mounted on the desired panel, return the first device found
return desiredDevice ?? allVideoDevices.FirstOrDefault();

 

 って、違うし!!

 デバイス系はこうやって実際にデバイスが取得できるかで判定するんですかね。

 

カメラの初期化

 

 カメラデバイスが見つかったら初期化処理を行います。

 

// Create MediaCapture and its settings
_mediaCapture = new MediaCapture();

// Register for a notification when video recording has reached the maximum time and when something goes wrong
_mediaCapture.RecordLimitationExceeded += MediaCapture_RecordLimitationExceeded;
_mediaCapture.Failed += MediaCapture_Failed;

var settings = new MediaCaptureInitializationSettings { VideoDeviceId = cameraDevice.Id };

// Initialize MediaCapture
try
{
    await _mediaCapture.InitializeAsync(settings);
    _isInitialized = true;
}
catch (UnauthorizedAccessException)
{
    Debug.WriteLine("The app was denied access to the camera");
}
catch (Exception ex)
{
    Debug.WriteLine("Exception when initializing MediaCapture with {0}: {1}", cameraDevice.Id, ex.ToString());
}

// If initialization succeeded, start the preview
if (_isInitialized)
{
    // Figure out where the camera is located
    if (cameraDevice.EnclosureLocation == null || cameraDevice.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Unknown)
    {
        // No information on the location of the camera, assume it's an external camera, not integrated on the device
        _externalCamera = true;
    }
    else
    {
        // Camera is fixed on the device
        _externalCamera = false;

        // Only mirror the preview if the camera is on the front panel
        _mirroringPreview = (cameraDevice.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Front);
    }

    await StartPreviewAsync();

    UpdateCaptureControls();
}

 

プレビュー表示

 

 画面にカメラ映像を表示するにはCaptureElementのSourceプロパティにMediaCaptureクラスのインスタンスを指定します。

 上記コードのStartPreviewAsyncの処理が以下です。

 

private async Task StartPreviewAsync()
{
    // Prevent the device from sleeping while the preview is running
    _displayRequest.RequestActive();

    // Set the preview source in the UI and mirror it if necessary
    PreviewControl.Source = _mediaCapture;
    PreviewControl.FlowDirection = _mirroringPreview ? FlowDirection.RightToLeft : FlowDirection.LeftToRight;

    // Start the preview
    try
    {
        await _mediaCapture.StartPreviewAsync();
        _isPreviewing = true;
    }
    catch (Exception ex)
    {
        Debug.WriteLine("Exception when starting the preview: {0}", ex.ToString());
    }

    // Initialize the preview to the current orientation
    if (_isPreviewing)
    {
        await SetPreviewRotationAsync();
    }
}

 

画像を撮影する

 

 画像を撮影します。

 

 var stream = new InMemoryRandomAccessStream();

try
{
    Debug.WriteLine("Taking photo...");
    await _mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), stream);
    Debug.WriteLine("Photo taken!");

    var photoOrientation = ConvertOrientationToPhotoOrientation(GetCameraOrientation());

    await ReencodeAndSavePhotoAsync(stream, photoOrientation);
}
catch (Exception ex)
{
    Debug.WriteLine("Exception when taking a photo: {0}", ex.ToString());
}

 

動画を撮影する

 

 動画も保存できます。

 

try
{
    // Create storage file in Pictures Library
    var videoFile = await KnownFolders.PicturesLibrary.CreateFileAsync("SimpleVideo.mp4", CreationCollisionOption.GenerateUniqueName);

    var encodingProfile = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Auto);

    // Calculate rotation angle, taking mirroring into account if necessary
    var rotationAngle = 360 - ConvertDeviceOrientationToDegrees(GetCameraOrientation());
    encodingProfile.Video.Properties.Add(RotationKey, PropertyValue.CreateInt32(rotationAngle));

    Debug.WriteLine("Starting recording...");

    await _mediaCapture.StartRecordToStorageFileAsync(encodingProfile, videoFile);
    _isRecording = true;

    Debug.WriteLine("Started recording!");
}
catch (Exception ex)
{
    Debug.WriteLine("Exception when starting video recording: {0}", ex.ToString());
}

 

録画を停止する

 

 録画を停止します。

 

await _mediaCapture.StopRecordAsync();

 CameraStarterKitプロジェクトは他にも回転の制御やOnNavigatedTo時やOnNavigatingFrom時の復旧、終了処理なども記述してあって、勉強になるサンプルだと感じました。


Please give us your valuable comment

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

このサイトはスパムを低減するために Akismet を使っています。コメントデータの処理方法の詳細はこちらをご覧ください