Sunday, 16 November 2014

Simple Webcam Video

Previously we used the CameraCaptureUI class to call a camera UI take a picture and pass it back to our application, this time lets do the same thing but with video instead.

to get started we need to as before we need to define our capabilities


Notice that as before we have webcam checked off, but we also included the webcam capability, this is a must, if you forget you're video capture wont work and the your app will let know it requires your permission.

next let's set up our UI

<Page
    x:Class="pc.Media.Video.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:pc.Media.Video"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Grid  Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="auto"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <Button x:Name="Record_BTN" Content="Record"/>
        <MediaElement Margin="100" x:Name="VideoPlayer" Grid.Column="1" />
    </Grid>

</Page>

just as before with the exceptiont that we're using our MediaElement instead of our image object, because of the fact that we have to show our video.

next lets' set up our codebehind

using System;
using Windows.Media.Capture;
using Windows.Storage;
using Windows.Storage.Streams;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

namespace pc.Media.Video
{
    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
            this.Record_BTN.Click += Record_BTN_Click;
        }

        async void Record_BTN_Click(object sender, RoutedEventArgs e)
        {
            var camera = new CameraCaptureUI();

            //wait for the image
            StorageFile video = await camera.CaptureFileAsync(CameraCaptureUIMode.Video);

            //Check if it was sent back
            if (video != null)
            {
                // open a stream to our sotrage file aka our video
                IRandomAccessStream stream = await video.OpenAsync(FileAccessMode.Read);
                VideoPlayer.SetSource(stream, video.ContentType);
            }
            else
            {
                await new MessageDialog("No Video recieved").ShowAsync();
            }
        }
    }
}


just as before we pass our video capture off to the CameraCaptureUI and it comes back with our storage file which we can manipulate however we please.