Windows 10 Universal Windows Platform – Video Recorder

Step 1

Download Visual Studio Community 2015 and install it onto your computer, if it’s already downloaded and installed select Launch to start Visual Studio Community 2015 or if it has already been downloaded and installed then start the application you may also need to Enable your device for development.

10-home

Step 2

Once Visual Studio Community 2015 has started select File, then New, then Project… from the Menu.

10-file-new-project

Step 3

From the New Project window select Visual C# from Installed, Templates then select Blank App (Windows Universal) from the list, then type in a Name and select a Location to save to before selecting Ok to create the Project.

10-new-project

Step 4

Once done select from the Menu, Project, then Add New Item…

10-project-add-new-item

Step 5

From the Add New Item window select Visual C# 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

10-add-new-item-library

Step 6

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 videoFilename = "video.mp4";
    private string filename;

    private MediaCapture capture;
    private InMemoryRandomAccessStream buffer;

    public static 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 excute two records 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(videoFilename, 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();
        });
    }
}

It should then appear as such:

10-library-videorecorder

Step 7

From the Solution Explorer select MainPage.xaml

10-mainpage

Step 8

Select from the Menu, View then Designer

10-designer

Step 9

The Design View will be displayed along with the XAML View and in this above <Grid Background=”{ThemeResource ApplicationPageBackgroundThemeBrush}”> enter the following XAML:

<Page.BottomAppBar>
	<AppBar IsOpen="True" IsSticky="True">
		<StackPanel Orientation="Horizontal">
			<AppBarButton Name="Record" Icon="Video" Label="Record" Click="Record_Click"/>
			<AppBarButton Name="Play" Icon="Play" Label="Play" Click="Play_Click"/>
		</StackPanel>
	</AppBar>
</Page.BottomAppBar>

While still in the XAML View below <Grid Background=”{ThemeResource ApplicationPageBackgroundThemeBrush}”> enter the following XAML:

<Grid Margin="20">
	<CaptureElement Name="Preview"/>
	<MediaElement Name="Display"/>
</Grid>

It should appear as such:

10-xaml-videorecorder

Step 10

Select from the Menu, View then Code

10-code

Step 11

Once in the Code View below the public MainPage() { … } the following should be entered:

public 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);
}

It should then appear as such:

10-code-videorecorder

Step 12

Then from the Solution Explorer select Package.appxmanifest

10-package

Step 13

Select from the Menu, View then Code

10-code

Step 14

The Code View will be displayed for the Package.appxmanifest and in this below <Capability Name=”internetClient” /> enter the following XML:

<DeviceCapability Name="microphone" />
<DeviceCapability Name="webcam" />

It should appear as such:

10-package-videorecorder

Step 15

That completes the Windows Universal Application so Save the Project then select the Debug and Local Machine option to run the Application

10-localmachine

Step 16

Once the Application has started the following should then appear

10-localmachine-run-videoecorder

Step 17

After the Application has started running if your Local Machine has access to a Microphone and Camera you can use the Record option to capture video then use Play to listen back to the recording

10-localmachine-ran-videoecorder

Step 18

To Exit the application select Stop Debugging in Visual Studio Community 2015

10-stop

Step 19

Another option is to run as a Windows Phone application, select Debug and select Emulator 10.0.1.0 WVGA 4 inch 512MB option to run the Application

10-emulator

Step 20

Once the Emulator has started the Application should then appear

10-emulator-run-videorecorder

Step 21

After the Application has started running if the Emulator has access to a Microphone and Camera you can use the Record option to capture video then use Play to listen back to the recording

10-emulator-ran-videorecorder

Step 22

To Exit the application select Stop Debugging in Visual Studio Community 2015

10-stop

Creative Commons License

Advertisements

One thought on “Windows 10 Universal Windows Platform – Video Recorder

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s