Video Recorder demonstrates how to use MediaCapture to record video
Step 1
If not already, follow Setup and Start on how to Install and get Started with Visual Studio 2017 or in Windows 10 choose Start, and then from the Start Menu find and select Visual Studio 2017.
Step 2
Once Visual Studio Community 2017 has started, from the Menu choose File, then New then Project…
Step 3
From New Project choose Visual C# from Installed, Templates then choose Blank App (Universal Windows) and then type in a Name and select a Location and then select Ok to create the Project
Step 4
Then in New Universal Windows Project you need to select the Target Version this should be at least the Windows 10 Fall Creators Update (10.0; Build 16299) and the Minimum Version to be the same.
The Target Version will control what features your application can use in Windows 10 so by picking the most recent version you’ll be able to take advantage of those features. To make sure you always have the most recent version, in Visual Studio 2017 select Tools Extensions and Updates… then and then see if there are any Updates
Step 5
Once done select from the Menu, Project, then Add New Item…
Step 6
From the Add New Item window select Visual C#, then Code from Installed then select Code File from the list, then type in the Name as Library.cs before selecting Add to add the file to the Project
Step 7
Once in the Code View for Library.cs the following should be entered:
using System; using System.Threading.Tasks; using Windows.Media.Capture; using Windows.Media.MediaProperties; using Windows.Storage; using Windows.Storage.Streams; using Windows.UI.Core; using Windows.UI.Xaml.Controls; public class Library { private const string file_name = "video.mp4"; private string _filename; private MediaCapture _capture; private InMemoryRandomAccessStream _buffer; public bool Recording; private async Task<bool> Init() { if (_buffer != null) { _buffer.Dispose(); } _buffer = new InMemoryRandomAccessStream(); if (_capture != null) { _capture.Dispose(); } try { MediaCaptureInitializationSettings settings = new MediaCaptureInitializationSettings { StreamingCaptureMode = StreamingCaptureMode.AudioAndVideo }; _capture = new MediaCapture(); await _capture.InitializeAsync(); _capture.RecordLimitationExceeded += (MediaCapture sender) => { Stop(); throw new Exception("Exceeded Record Limitation"); }; _capture.Failed += (MediaCapture sender, MediaCaptureFailedEventArgs errorEventArgs) => { Recording = false; throw new Exception(string.Format("Code: {0}. {1}", errorEventArgs.Code, errorEventArgs.Message)); }; } catch (Exception ex) { if (ex.InnerException != null && ex.InnerException.GetType() == typeof(UnauthorizedAccessException)) { throw ex.InnerException; } throw; } return true; } public async void Record(CaptureElement preview) { await Init(); preview.Source = _capture; await _capture.StartPreviewAsync(); await _capture.StartRecordToStreamAsync(MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Auto), _buffer); if (Recording) throw new InvalidOperationException("Cannot execute two recordings at the same time"); Recording = true; } public async void Stop() { await _capture.StopRecordAsync(); Recording = false; } public async Task Play(CoreDispatcher dispatcher, MediaElement playback) { IRandomAccessStream video = _buffer.CloneStream(); if (video == null) throw new ArgumentNullException("buffer"); StorageFolder storageFolder = Windows.ApplicationModel.Package.Current.InstalledLocation; if (!string.IsNullOrEmpty(_filename)) { StorageFile original = await storageFolder.GetFileAsync(_filename); await original.DeleteAsync(); } await dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () => { StorageFile storageFile = await storageFolder.CreateFileAsync(file_name, CreationCollisionOption.GenerateUniqueName); _filename = storageFile.Name; using (IRandomAccessStream fileStream = await storageFile.OpenAsync(FileAccessMode.ReadWrite)) { await RandomAccessStream.CopyAndCloseAsync(video.GetInputStreamAt(0), fileStream.GetOutputStreamAt(0)); await video.FlushAsync(); video.Dispose(); } IRandomAccessStream stream = await storageFile.OpenAsync(FileAccessMode.Read); playback.SetSource(stream, storageFile.FileType); playback.Play(); }); } }
In the Library.cs there are using statements to include the necessary functionality. MediaCapture is used to capture the video from connected camera or webcam by the application, the Init Method sets up the recording including configuring the necessary Events for any issues including RecordLimitationExceeded and Failed. The Record Method is used to start recording video using StartRecordToStreamAsync of MediaCapture. Play is used to playback any recorded video using a MediaElement Control set to the file source that was recorded to.
Step 8
In the Solution Explorer select MainPage.xaml
Step 9
From the Menu choose View and then Designer
Step 10
The Design View will be displayed along with the XAML View and in this between the Grid and /Grid elements, enter the following XAML:
<Grid Margin="50"> <CaptureElement Name="Preview"/> <MediaElement Name="Display"/> </Grid> <CommandBar VerticalAlignment="Bottom"> <AppBarButton Name="Record" Icon="Memo" Label="Record" Click="Record_Click"/> <AppBarButton Name="Play" Icon="Play" Label="Play" Click="Play_Click"/> </CommandBar>
The first block of XAML the main user interface of the Application, this features a Grid with a CaptureElement to show any video being recorder and a MediaElement to show video playback. The second block of XAML is the CommandBar which contains the Record and Play commands to perform the actions of the Video Recorder.
Step 11
From the Menu choose View and then Code
Step 12
Once in the Code View, below the end of public MainPage() { … } the following Code should be entered:
Library library = new Library(); private void Record_Click(object sender, RoutedEventArgs e) { if (library.Recording) { Preview.Source = null; library.Stop(); Record.Icon = new SymbolIcon(Symbol.Video); } else { Display.Source = null; library.Record(Preview); Record.Icon = new SymbolIcon(Symbol.VideoChat); } } private async void Play_Click(object sender, RoutedEventArgs e) { await library.Play(Dispatcher, Display); }
Below the MainPage() Method an instance of the Library Class is created. Record_Click is used to start a Video recording or if the Recording flag is set it will Stop the recording, Play_Click is used to playback any Video recording.
Step 13
In the Solution Explorer select Package.appxmanifest
Step 14
From the Menu choose View and then Designer
Step 15
Finally in the Package.appxmanifest select Capabilities and then make sure the Microphone and Webcam options are checked
Step 16
That completes the Universal Windows Platform Application so Save the Project then in Visual Studio select the Local Machine to run the Application
Step 17
After the Application has started running if your Local Machine has access to a Microphone and Webcam you can use the Record option to capture video then use Play to play back the recorded Video
Step 18
To Exit the Application select the Close button in the top right of the Application