Video

パソコンのカメラで動画を撮影します。

前田稔の超初心者のプログラム入門

プログラムの説明

  1. パソコンのカメラを使って動画を撮影して保存します。
    Visual Studio を起動して[空白アプリ(ユニバーサル Windows)]を構築して下さい。
    プロジェクトの名前を Samples に合わせて CameraStarterKit とします。
  2. MainPage.xaml と MainPage.xaml.cs を下記のソースで置き換えます。
  3. ソリューションエクスプローラの参照を右クリックして [参照の追加][拡張] からDLLを追加します。

  4. Package.appxmanifest をダブルクリックして、設定画面を表示します。
    機能タグから「Web カメラ, ピクチャ ライブラリ, マイク」をチェックして下さい。

  5. コンパイル&実行するとカメラの使用許可が求められます。
    使用を許可するとパソコン画面にカメラで撮影中の画像が表示されます。
    動画アイコンをクリックすると、撮影が開始されます。
    撮影中に動画アイコンをクリックすると PC\画像\SimpleVideo.mp4 に保存されます。
  6. MainPage.xaml の後部に "VideoButton" を追加して下さい。
    ボタンをクリックすると VideoButton_Click() 関数が呼び出されます。
                <Button Name="VideoButton" Click="VideoButton_Click" IsEnabled="False">
                    <Grid>
                        <Ellipse x:Name="StartRecordingIcon" Fill="Red" Width="20" Height="20"/>
                        <Rectangle x:Name="StopRecordingIcon" Fill="White" Width="20" Height="20" Visibility="Collapsed"/>
                    </Grid>
                </Button>
            </StackPanel>
        </Grid>
    </Page>
    
  7. MainPage.xaml.cs にカメラの動画撮影の機能を追加したソースコードです。
    using System;
    using System.Diagnostics;
    using System.Linq;
    using System.Threading.Tasks;
    using Windows.ApplicationModel;
    using Windows.Devices.Enumeration;
    using Windows.Foundation;
    using Windows.Foundation.Metadata;
    using Windows.Graphics.Display;
    using Windows.Media.Capture;
    using Windows.Media.MediaProperties;
    using Windows.Storage;
    using Windows.System.Display;
    using Windows.UI.Core;
    using Windows.UI.Xaml;
    using Windows.UI.Xaml.Controls;
    using Windows.UI.Xaml.Navigation;
    
    namespace CameraStarterKit
    {
        public sealed partial class MainPage : Page
        {
            private static readonly Guid RotationKey = new Guid("C380465D-2271-428C-9B83-ECEA3B4A85C1");
    
            // Folder in which the captures will be stored (initialized in SetupUiAsync)
            private StorageFolder _captureFolder = null;
            // Prevent the screen from sleeping while the camera is running
            private readonly DisplayRequest _displayRequest = new DisplayRequest();
    
            // MediaCapture and its state variables
            private MediaCapture _mediaCapture;
            private bool _isInitialized;
            private bool _isPreviewing;
            private bool _isRecording;
    
            // UI state
            private bool _isSuspending;
            private bool _isActivePage;
            private bool _isUIActive;
            private Task _setupTask = Task.CompletedTask;
    
            // Information about the camera device
            private bool _mirroringPreview;
            private bool _externalCamera;
    
            public MainPage()
            {
                this.InitializeComponent();
    
                // Do not cache the state of the UI when suspending/navigating
                NavigationCacheMode = NavigationCacheMode.Disabled;
            }
    
            private void Application_Suspending(object sender, SuspendingEventArgs e)
            {
                _isSuspending = false;
    
                var deferral = e.SuspendingOperation.GetDeferral();
                var task = Dispatcher.RunAsync(CoreDispatcherPriority.High, async () =>
                {
                    await SetUpBasedOnStateAsync();
                    deferral.Complete();
                });
            }
    
            protected override async void OnNavigatedTo(NavigationEventArgs e)
            {
                // Useful to know when to initialize/clean up the camera
                Application.Current.Suspending += Application_Suspending;
                Window.Current.VisibilityChanged += Window_VisibilityChanged;
    
                _isActivePage = true;
                await SetUpBasedOnStateAsync();
            }
    
            private async void Window_VisibilityChanged(object sender, VisibilityChangedEventArgs args)
            {
                await SetUpBasedOnStateAsync();
            }
    
            private async void VideoButton_Click(object sender, RoutedEventArgs e)
            {
                if (!_isRecording)
                {
                    await StartRecordingAsync();
                }
                else
                {
                    await StopRecordingAsync();
                }
    
                // After starting or stopping video recording, update the UI to reflect the MediaCapture state
                UpdateCaptureControls();
            }
    
            private async Task InitializeCameraAsync()
            {
                if (_mediaCapture == null)
                {
                    // Attempt to get the back camera if one is available, but use any camera device if not
                    var cameraDevice = await FindCameraDeviceByPanelAsync(Windows.Devices.Enumeration.Panel.Back);
    
                    if (cameraDevice == null)
                    {
                        Debug.WriteLine("No camera device found!");
                        return;
                    }
    
                    // Create MediaCapture and its settings
                    _mediaCapture = new MediaCapture();
    
                    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");
                    }
    
                    // 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();
                    }
                }
            }
    
            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
                await _mediaCapture.StartPreviewAsync();
                _isPreviewing = true;
            }
    
            private async Task StopPreviewAsync()
            {
                // Stop the preview
                _isPreviewing = false;
                await _mediaCapture.StopPreviewAsync();
    
                // Use the dispatcher because this method is sometimes called from non-UI threads
                await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    // Cleanup the UI
                    PreviewControl.Source = null;
    
                    // Allow the device screen to sleep now that the preview is stopped
                    _displayRequest.RequestRelease();
                });
            }
    
            private async Task StartRecordingAsync()
            {
                try
                {
                    // Create storage file for the capture
                    var videoFile = await _captureFolder.CreateFileAsync("SimpleVideo.mp4", CreationCollisionOption.GenerateUniqueName);
    
                    var encodingProfile = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Auto);
    
                    var rotationAngle = 0;
                    encodingProfile.Video.Properties.Add(RotationKey, PropertyValue.CreateInt32(rotationAngle));
    
                    Debug.WriteLine("Starting recording to " + videoFile.Path);
    
                    await _mediaCapture.StartRecordToStorageFileAsync(encodingProfile, videoFile);
                    _isRecording = true;
    
                    Debug.WriteLine("Started recording!");
                }
                catch (Exception ex)
                {
                    // File I/O errors are reported as exceptions
                    Debug.WriteLine("Exception when starting video recording: " + ex.ToString());
                }
            }
    
            private async Task StopRecordingAsync()
            {
                Debug.WriteLine("Stopping recording...");
    
                _isRecording = false;
                await _mediaCapture.StopRecordAsync();
    
                Debug.WriteLine("Stopped recording!");
            }
    
            private async Task CleanupCameraAsync()
            {
                if (_isInitialized)
                {
                    // If a recording is in progress during cleanup, stop it to save the recording
                    if (_isRecording)
                    {
                        await StopRecordingAsync();
                    }
    
                    if (_isPreviewing)
                    {
                        await StopPreviewAsync();
                    }
    
                    _isInitialized = false;
                }
    
                if (_mediaCapture != null)
                {
                    _mediaCapture.Dispose();
                    _mediaCapture = null;
                }
            }
    
            private async Task SetUpBasedOnStateAsync()
            {
                // Avoid reentrancy: Wait until nobody else is in this function.
                while (!_setupTask.IsCompleted)
                {
                    await _setupTask;
                }
    
                bool wantUIActive = _isActivePage && Window.Current.Visible && !_isSuspending;
    
                if (_isUIActive != wantUIActive)
                {
                    _isUIActive = wantUIActive;
    
                    Func<Task> setupAsync = async () =>
                    {
                        if (wantUIActive)
                        {
                            await SetupUiAsync();
                            await InitializeCameraAsync();
                        }
                        else
                        {
                            await CleanupCameraAsync();
                            await CleanupUiAsync();
                        }
                    };
                    _setupTask = setupAsync();
                }
    
                await _setupTask;
            }
    
            private async Task SetupUiAsync()
            {
                // Attempt to lock page to landscape orientation to prevent the CaptureElement from rotating, as this gives a better experience
                DisplayInformation.AutoRotationPreferences = DisplayOrientations.Landscape;
    
                // Hide the status bar
                if (ApiInformation.IsTypePresent("Windows.UI.ViewManagement.StatusBar"))
                {
                    await Windows.UI.ViewManagement.StatusBar.GetForCurrentView().HideAsync();
                }
    
                var picturesLibrary = await StorageLibrary.GetLibraryAsync(KnownLibraryId.Pictures);
                // Fall back to the local app storage if the Pictures Library is not available
                _captureFolder = picturesLibrary.SaveFolder ?? ApplicationData.Current.LocalFolder;
            }
    
            private async Task CleanupUiAsync()
            {
                // Show the status bar
                if (ApiInformation.IsTypePresent("Windows.UI.ViewManagement.StatusBar"))
                {
                    await Windows.UI.ViewManagement.StatusBar.GetForCurrentView().ShowAsync();
                }
    
                // Revert orientation preferences
                DisplayInformation.AutoRotationPreferences = DisplayOrientations.None;
            }
    
            private void UpdateCaptureControls()
            {
                // The buttons should only be enabled if the preview started sucessfully
                VideoButton.IsEnabled = _isPreviewing;
    
                // Update recording button to show "Stop" icon instead of red "Record" icon
                StartRecordingIcon.Visibility = _isRecording ? Visibility.Collapsed : Visibility.Visible;
                StopRecordingIcon.Visibility = _isRecording ? Visibility.Visible : Visibility.Collapsed;
            }
    
            private static async Task<DeviceInformation> FindCameraDeviceByPanelAsync(Windows.Devices.Enumeration.Panel desiredPanel)
            {
                // 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();
            }
    
        }
    }
    

超初心者のプログラム入門(C# Frame Work)