#

 

 

Folgende C# Code Beschreibung zeigt eine voll funktionierenden Webcam Recorder.

Dabei werden die Web-Kamera und das Mikrofon Audio Signal automatisch aufgenommen und in einer .mp4 Datei als Video gespeichert.

 

 

Video Beschreibung

 

 

Wichtigste Code-Bereiche:

 

Kamera anzeigen

Damit man die Kamera sehen kann, muss man erst mal die Kamera starten

ctlCamera.Source = _mediaCapture;

await _mediaCapture.StartPreviewAsync();

 

 

Aufnahme Starten

Für die Aufnahme benötigt man einen Memory-Stream. Dieser wird durch das MediaCapture gefüllt.

_mediaStream = new InMemoryRandomAccessStream();

MediaEncodingProfile encodingProfile = MediaEncodingProfile.CreateMp4(_encodingQuality);

await _mediaCapture.StartRecordToStreamAsync(encodingProfile, _mediaStream);

 

 

Aufnahme Stoppen

Zum Beenden muss man dem MediaCapture nur die Stop Anweisung geben

await _mediaCapture.StopRecordAsync();

await save_Recorded_Data_to_File();

 

Aufnahme als mp4-Datei  speichern

Anschliessend muss man den Memoryspeicher auf eine Datei übertragen.

using (var dataReader = new DataReader(record_Stream.GetInputStreamAt(0)))

{

  await dataReader.LoadAsync((uint)record_Stream.Size);

  byte[] buffer = new byte[(int)record_Stream.Size];

  dataReader.ReadBytes(buffer);

  await FileIO.WriteBytesAsync(save_File, buffer);

  }

 

 

 

Kompletter C# Code:

using System;

using Windows.UI.Xaml;

using Windows.UI.Xaml.Controls;

using System.Threading.Tasks;

using Windows.Media.Capture;

using Windows.Media.MediaProperties;

using Windows.Storage;

using Windows.Storage.Pickers;

using Windows.Storage.Streams;

using Windows.UI.Popups;

using MediaCaptureApiVideo;

using Windows.Storage.AccessCache;

using Windows.UI.Xaml.Media;

 

namespace record_Video

{

 

    public sealed partial class MainPage : Page

    {

 

        #region Variables

        private MediaCapture _mediaCapture;

        private IRandomAccessStream _mediaStream;

        private VideoEncodingFormat _encodingFormat;

        private VideoEncodingQuality _encodingQuality;

        private VideoRecordingState _recordingState;

        #endregion  /Variables

 

 

        #region Page   

        public MainPage()

        {

            //-------------< MainPage() >-------------

            this.InitializeComponent();

            Task init = setup();

            //-------------</ MainPage() >-------------

        }

        #endregion  /Page

 

        #region Buttons

        //--------------------------< Region: Buttons >--------------------------

        private void btnRecord_Click(object sender, RoutedEventArgs e)

        {

            SolidColorBrush fill_Brush = rectRecord.Fill as SolidColorBrush;

            if (fill_Brush.Color.R > 0)

            {

                rectRecord.Fill = new SolidColorBrush(Windows.UI.Colors.Black);

                record_stop();

            }

            else

            {

                rectRecord.Fill = new SolidColorBrush(Windows.UI.Colors.Red);

                record_start();

            }

 

        }

 

 

        private async void btnSetFolder_Click(object sender, RoutedEventArgs e)

        {

 

            //< open FolderPicker to get Read Permission >

            FolderPicker picker = new FolderPicker();

            picker.FileTypeFilter.Add("*");

            picker.ViewMode = PickerViewMode.Thumbnail;

            picker.SuggestedStartLocation = PickerLocationId.Desktop;

            picker.CommitButtonText = "This Folder";

            StorageFolder objPicked_Folder = await picker.PickSingleFolderAsync();

 

            //< Bilder laden >

            if (objPicked_Folder != null)

            {

                string sPath = objPicked_Folder.Path;

                //< Zugriff global speichern >

                StorageApplicationPermissions.FutureAccessList.Add(objPicked_Folder, "metadata");

                //< Zugriff global speichern >

                tbxFolder.Text = sPath;

 

                //< Save Setting >

                Windows.Storage.ApplicationData.Current.LocalSettings.Values["Folder_to_Save"] = sPath ;

                //</ Save Setting >

            }

            //</ open FolderPicker to get Read Permission >

        }

 

 

        private async void btnOpenFolder_Click(object sender, RoutedEventArgs e)

        {

            //----------------< btnOpenFolder_Click() >----------------

            String sPath = ApplicationData.Current.LocalSettings.Values["Folder_to_Save"] as string;

            StorageFolder folder = await StorageFolder.GetFolderFromPathAsync(sPath);

 

            //< Dateiexplorer oeffnen >

            await Windows.System.Launcher.LaunchFolderAsync(folder);

            //</ Dateiexplorer oeffnen >

            //----------------</ btnOpenFolder_Click() >----------------

        }

 

        //--------------------------</ Region: Buttons >--------------------------

        #endregion /Buttons

 

 

        #region Methods: Setup

        private async Task setup()

        {

            //-------------< init_Capture() >-------------

            _encodingFormat = VideoEncodingFormat.Mp4;

            _encodingQuality = VideoEncodingQuality.Auto; // .HD1080p;           

            await init_Capture();

            init_Camera();

           

            //< Get Setting >

            tbxFolder.Text= ApplicationData.Current.LocalSettings.Values["Folder_to_Save"] as string ;

            //</ Get Setting >

            //-------------</ init_Capture() >-------------

        }

        #endregion /Methods: Setup

 

        #region Methods: Capture

        private async Task init_Capture()

        {

            //-------------< init_Capture() >-------------

            _mediaCapture = new MediaCapture();

            MediaCaptureInitializationSettings mediaCaptureInitSettings = new MediaCaptureInitializationSettings()

            {

                StreamingCaptureMode = StreamingCaptureMode.AudioAndVideo

            };

            await _mediaCapture.InitializeAsync(mediaCaptureInitSettings);

            _mediaCapture.Failed += MediaCaptureOnFailed;

            _mediaCapture.RecordLimitationExceeded += MediaCaptureOnRecordLimitationExceeded;

            //-------------</ init_Capture() >-------------

        }

 

        private async void record_start()

        {

            //-------------< record_start() >-------------

            _mediaStream = new InMemoryRandomAccessStream();

            MediaEncodingProfile encodingProfile = MediaEncodingProfile.CreateMp4(_encodingQuality);

            await _mediaCapture.StartRecordToStreamAsync(encodingProfile, _mediaStream);

            //-------------</ record_start () >-------------

        }

 

        private async void record_stop()

        {

            //-------------< record_stop  () >-------------

            await _mediaCapture.StopRecordAsync();

            await save_Recorded_Data_to_File();

            //-------------</ record_stop  () >-------------

        }

 

        private async void init_Camera()

        {

            //-------------< init_Camera() >-------------

            if (_recordingState != VideoRecordingState.Recording && _recordingState != VideoRecordingState.Previewing)

            {

                ctlCamera.Source = _mediaCapture;

                await _mediaCapture.StartPreviewAsync();

            }

            //-------------</ init_Camera() >-------------

        }

 

        private async Task save_Recorded_Data_to_File()

        {

            string sPath = (string)ApplicationData.Current.LocalSettings.Values["Folder_To_Save"];

            StorageFolder objFolder = await StorageFolder.GetFolderFromPathAsync(sPath);

            //< Kontrolle >

            if (objFolder == null)

            {

                fl_Sys_Messagebox("The folder could not be opened;", "Open Folder Path");

                return;

            }

            //< Kontrolle >

 

 

            IRandomAccessStream record_Stream = _mediaStream;

 

            string sFilename = DateTime.Now.ToString("yyyy-MM-yy hhmmss") + " ScreenRecord" + ".mp4";

            StorageFile save_File = await objFolder.CreateFileAsync(sFilename, Windows.Storage.CreationCollisionOption.ReplaceExisting);

            if (save_File != null)

            {

                using (var dataReader = new DataReader(record_Stream.GetInputStreamAt(0)))

                {

                    await dataReader.LoadAsync((uint)record_Stream.Size);

                    byte[] buffer = new byte[(int)record_Stream.Size];

                    dataReader.ReadBytes(buffer);

                    await FileIO.WriteBytesAsync(save_File, buffer);

                }

            }

        }

        #endregion /Methods: Capture

 

 

        #region Events: MediaCapture_events

        private async void MediaCaptureOnFailed(MediaCapture sender, MediaCaptureFailedEventArgs erroreventargs)

        {

            await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>

            {

                var warningMessage = new MessageDialog(String.Format("The video capture failed: {0}", erroreventargs.Message), "Capture Failed");

                await warningMessage.ShowAsync();

            });

        }

        private async void MediaCaptureOnRecordLimitationExceeded(MediaCapture sender)

        {

            await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>

            {

                await _mediaCapture.StopRecordAsync();

                var warningMessage = new MessageDialog(String.Format("The video capture has exceeded its maximum length: {0}",

                    "Capture Halted"));

                await warningMessage.ShowAsync();

            });

        }

        #endregion /Events: MediaCapture_events

 

 

        #region Sys-Funktionen

        //========================< Region: Sys-Funktionen >========================

        private async void fl_Sys_Messagebox(string Text, string Title)

        {

            MessageDialog dialog = new MessageDialog(Text, Title);

            await dialog.ShowAsync();

        }

        private async Task UpdateStatus(string status)

        {

            await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => Status.Text = status);

        }

 

 

        //========================</ Region: Sys-Funktionen >========================

        #endregion

 

 

    }

}

 

 

 

 

Xaml Code

<Page

    x:Class="record_Video.MainPage"

    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

    xmlns:local="using:record_Video"

    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"

    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

    mc:Ignorable="d" >

 

    <Grid HorizontalAlignment="Stretch" VerticalAlignment="Stretch" >

        <Grid.RowDefinitions>

            <RowDefinition Height="*"/>

            <RowDefinition Height="40"/>

            <RowDefinition Height="32"/>

        </Grid.RowDefinitions>

 

        <CaptureElement Name="ctlCamera" Grid.Row="0" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"  ></CaptureElement>

 

        <StackPanel HorizontalAlignment="Left"  Grid.Row="1">

            <StackPanel Name="VideoPanel" HorizontalAlignment="Center" Orientation="Horizontal">

                <Button Name="btnRecord" Click="btnRecord_Click"  >

                    <Rectangle x:Name="rectRecord" RadiusX="15" RadiusY="15" Height="30" Width="30" Fill="Black" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"   ></Rectangle>

                </Button>

            </StackPanel>

            <TextBlock Name="Status" Foreground="Orange" Margin="0" FontSize="14"></TextBlock>

        </StackPanel>

       

        <StackPanel x:Name="pnlSave" Grid.Row="3" Orientation="Horizontal" HorizontalAlignment="Stretch" >

            <Button x:Name="btnSetFolder" Click="btnSetFolder_Click">Folder</Button>

            <Button x:Name="btnOpenFolder" Click="btnOpenFolder_Click" Foreground ="Orange" >

                <SymbolIcon Symbol="Folder" ></SymbolIcon></Button>

            <TextBlock x:Name="tbxFolder" MinWidth="200" VerticalAlignment="Center" HorizontalAlignment="Stretch"  ></TextBlock>

        </StackPanel>

    </Grid>

</Page>

 

 

Mobile

.

0123movie.net