Out of the ordinary Windows Phone (41) - 8 camera and photo: capturing video and

Recommended for you: Get network issues from WhatsUp Gold. Not end users.

[Download]


Out of the ordinary Windows Phone (41) - 8 camera and photo: capturing video and audio by AudioVideoCaptureDevice



Author: webabcd


Introduction
Out of the ordinary windows phone 8 camera and photo



Example
Demonstration of AudioVideoCaptureDevice (wp8) application
CameraAndPhoto/AudioVideoCaptureDeviceDemo.xaml

<phone:PhoneApplicationPage
    x:Class="Demo.CameraAndPhoto.AudioVideoCaptureDeviceDemo"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait" Orientation="Portrait"
    mc:Ignorable="d"
    shell:SystemTray.IsVisible="True">

    <Grid x:Name="LayoutRoot" Background="Transparent">
        <StackPanel>

            <StackPanel Orientation="Horizontal">
                <Canvas Width="240" Height="180" RenderTransformOrigin="0.5 0.5">
                    <Canvas.Background>
                        <VideoBrush x:Name="videoBrush" />
                    </Canvas.Background>
                    <Canvas.RenderTransform>
                        <RotateTransform x:Name="rt" />
                    </Canvas.RenderTransform>
                </Canvas>
                <MediaElement Name="mediaElement" Width="240" Height="180" />
            </StackPanel>

            <StackPanel Orientation="Horizontal" Margin="0 50 0 0">
                <Button Name="btnCapture" Content="The video" Click="btnCapture_Click" />
                <Button Name="btnStop" Content="Stop it" Click="btnStop_Click" IsEnabled="False" />
                <Button Name="btnPlay" Content="Play" Click="btnPlay_Click" />
            </StackPanel>

            <TextBlock x:Name="lblMsg" TextWrapping="Wrap" Margin="0 10 0 0" />

        </StackPanel>
    </Grid>

</phone:PhoneApplicationPage>


CameraAndPhoto/AudioVideoCaptureDeviceDemo.xaml.cs

/*
 * Demonstration of AudioVideoCaptureDevice (wp8) application
 * 
 * On the CaptureSource, FileSink (WP7) applications
 * http://www.cnblogs.com/webabcd/archive/2012/08/13/2635698.html
 * http://www.cnblogs.com/webabcd/archive/2012/08/15/2639428.html
 * 
 * 
 * Note: 
 * The need to increase the configuration in manifest <Capability Name="ID_CAP_ISV_CAMERA" /> <Capability Name="ID_CAP_MICROPHONE" /> <Capability Name="ID_CAP_MEDIALIB_PHOTO" />
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using Microsoft.Phone.Controls;
using Windows.Phone.Media.Capture;
using Microsoft.Devices;
using Windows.Storage.Streams;
using Windows.Storage;
using Microsoft.Phone.Tasks;

namespace Demo.CameraAndPhoto
{
    public partial class AudioVideoCaptureDeviceDemo : PhoneApplicationPage
    {
        private AudioVideoCaptureDevice _captureDevice;
        private IRandomAccessStream _stream;

        public AudioVideoCaptureDeviceDemo()
        {
            InitializeComponent();

            this.Loaded += AudioVideoCaptureDeviceDemo_Loaded;
        }

        private async void AudioVideoCaptureDeviceDemo_Loaded(object sender, RoutedEventArgs e)
        {
            // The class description
            Summary();

            // If there is a rear camera
            if (AudioVideoCaptureDevice.AvailableSensorLocations.Contains(CameraSensorLocation.Back))
            {
                // Available resolution rear camera when the camera
                IReadOnlyList<Windows.Foundation.Size> supportedResolutions = AudioVideoCaptureDevice.GetAvailableCaptureResolutions(CameraSensorLocation.Back);
                Windows.Foundation.Size resolution = supportedResolutions[0];

                try
                {
                    // Let the rear camera to capture video content specified resolution
                    _captureDevice = await AudioVideoCaptureDevice.OpenAsync(CameraSensorLocation.Back, resolution);
                    // AudioVideoCaptureDevice.OpenForVideoOnlyAsync() - only to capture video
                    // AudioVideoCaptureDevice.OpenForAudioOnlyAsync() - only capture audio

                    // Trigger recording failure events
                    _captureDevice.RecordingFailed += _captureDevice_RecordingFailed;


                    /*
                     * SetCaptureResolutionAsync() Set camera resolution
                     * CaptureResolution - get current camera resolution
                     * The VideoEncodingFormat video coding format - current
                     * Audio coding format AudioEncodingFormat - current
                     * FocusRegion - focus area
                     * SensorLocation - the current camera position (CameraSensorLocation enumeration: Back or Front)
                     * SensorRotationInDegrees - get a camera sensor with respect to the degree of rotation of the screen
                     * FocusAsync() - AF
                     * ResetFocusAsync() Reset focus
                     */


                    /*
                     * The KnownCameraAudioVideoProperties property sets include
                     *     VideoFrameRate - captured video frames per second
                     *     H264EncodingProfile - H264 coded profile (H264EncoderProfile Mei Ju)
                     *     H264EncodingLevel - H264 coded level (H264EncoderLevel Mei Ju)
                     *     H264EnableKeyframes - whether to enable the key frame
                     *     H264QuantizationParameter - QP value, detailed information at low QP will retain most of the space, so as to achieve the best quality, high QP will result in quality to a certain degree of loss, but it can help to achieve low bit rate coder
                     *     H264RequestDropNextNFrames - specifies the coder should discard
                     *     H264RequestIdrFrame - when this property is set to true, the system requests coding process is instantaneous decoding refresh(IDR)
                     *     UnmuteAudioWhileRecording - when this property is set to true, can cancel mute audio during recording
                     *     How to use the flash VideoTorchMode - VIDEO (VideoTorchMode enumeration: Off, Auto, On)
                     *     Brightness flash video VideoTorchPower, no unit and different devices with different values of
                     */
                    _captureDevice.SetProperty(KnownCameraAudioVideoProperties.H264EncodingProfile, H264EncoderProfile.Baseline);


                    /*
                     * The KnownCameraGeneralProperties property sets include
                     *     The range AutoFocusRange autofocus (AutoFocusRange enumeration, including macro etc.)
                     *     The rotation angle of EncodeWithOrientation video coding, must be a multiple of 90
                     *     The rotation angle of SpecifiedCaptureOrientation metadata, must be a multiple of 90
                     *     IsShutterSoundEnabledByUser - whether the user has enabled the shutter sound, read-only
                     *     Whether the IsShutterSoundRequiredForRegion - running the application areas need shutter sound (some area in order to protect the privacy requirements, photography or video must have the shutter sound), read-only
                     *     PlayShutterSoundOnCapture - specifies the shutter sound is played when capturing
                     *     ManualFocusPosition manual focus position
                     */
                    _captureDevice.SetProperty(KnownCameraGeneralProperties.AutoFocusRange, AutoFocusRange.Normal);
                    _captureDevice.SetProperty(KnownCameraGeneralProperties.EncodeWithOrientation, _captureDevice.SensorRotationInDegrees);


                    // Access to the specified attribute values
                    // _captureDevice.GetProperty(KnownCameraGeneralProperties.IsShutterSoundEnabledByUser);

                    /*
                     * Access to the specified range allowed by the current camera class attribute values in the range of
                     */
                    // AudioVideoCaptureDevice.GetSupportedPropertyRange(CameraSensorLocation.Back, KnownCameraAudioVideoProperties.H264QuantizationParameter);

                    /*
                     * Get a list of values for the specified value attributes in the current camera allowed in
                     */
                    // AudioVideoCaptureDevice.GetSupportedPropertyValues(CameraSensorLocation.Back, KnownCameraAudioVideoProperties.H264EncodingProfile);

                    // Captured content display
                    videoBrush.SetSource(_captureDevice); // Extension methods from: Microsoft.Devices.CameraVideoBrushExtensions

                    rt.Angle = _captureDevice.SensorRotationInDegrees;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }
            else
            {
                MessageBox.Show("No rear camera");
            }
        }

        // Video failure
        void _captureDevice_RecordingFailed(AudioVideoCaptureDevice sender, CaptureFailedEventArgs args)
        {
            this.Dispatcher.BeginInvoke(delegate()
            {
                MessageBox.Show("error: " + args.ErrorCode.ToString());
            });
        }

        // To start recording
        private async void btnCapture_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // Gets the application data folder
                StorageFolder applicationFolder = ApplicationData.Current.LocalFolder;

                // Create the file specified in the application data folder
                StorageFile storageFile = await applicationFolder.CreateFileAsync("webabcdTest.mp4", CreationCollisionOption.ReplaceExisting);

                // Open a file stream, ready to write video data
                _stream = await storageFile.OpenAsync(FileAccessMode.ReadWrite);

                // Video recording to the specified stream
                await _captureDevice.StartRecordingToStreamAsync(_stream);

                btnCapture.IsEnabled = false;
                btnStop.IsEnabled = true;

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        // Stop recording
        private async void btnStop_Click(object sender, RoutedEventArgs e)
        {
            // Stop recording
            await _captureDevice.StopRecordingAsync();
            _stream.Dispose();

            btnCapture.IsEnabled = true;
            btnStop.IsEnabled = false;
        }

        // Play recorded content
        private void btnPlay_Click(object sender, RoutedEventArgs e)
        {
            // Start the media player, play recorded content
            MediaPlayerLauncher mediaPlayerLauncher = new MediaPlayerLauncher();

            // new Uri("webabcdTest.mp4", UriKind.Relative) With MediaLocationType.Data, you will be first in the app store's Local directory to find, can't find the Local/IsolatedStorage directory to find
            mediaPlayerLauncher.Media = new Uri("webabcdTest.mp4", UriKind.Relative);
            mediaPlayerLauncher.Location = MediaLocationType.Data;
            mediaPlayerLauncher.Controls = MediaPlaybackControls.Pause | MediaPlaybackControls.Stop;
            mediaPlayerLauncher.Orientation = MediaPlayerOrientation.Landscape;

            mediaPlayerLauncher.Show();
        }


        private void Summary()
        {
            lblMsg.Text = "";

            // To get the phone available camera
            foreach (CameraSensorLocation csl in AudioVideoCaptureDevice.AvailableSensorLocations)
            {
                // Back or Front
                lblMsg.Text += "The camera: " + csl.ToString();
                lblMsg.Text += System.Environment.NewLine;


                // Camera supported resolution
                lblMsg.Text += "The available resolution camera: ";
                foreach (var size in AudioVideoCaptureDevice.GetAvailableCaptureResolutions(csl))
                {
                    lblMsg.Text += size.Width + "*" + size.Height + " ";
                }
                lblMsg.Text += System.Environment.NewLine;
                lblMsg.Text += System.Environment.NewLine;


                // See the previous article about CameraButtons: http://www.cnblogs.com/webabcd/archive/2012/08/15/2639428.html
                // The CameraButtons.ShutterKeyHalfPressed event, CameraButtons.ShutterKeyPressed event, CameraButtons.ShutterKeyReleased event
            }


            lblMsg.Text += "Video coding format supported by the terminal: ";
            foreach (CameraCaptureVideoFormat format in AudioVideoCaptureDevice.SupportedVideoEncodingFormats)
            {
                lblMsg.Text += format.ToString() + " ";
            }
            lblMsg.Text += System.Environment.NewLine;


            lblMsg.Text += "Audio coding format supported by the terminal: ";
            foreach (CameraCaptureAudioFormat format in AudioVideoCaptureDevice.SupportedAudioEncodingFormats)
            {
                lblMsg.Text += format.ToString() + " ";
            }
            lblMsg.Text += System.Environment.NewLine;
        }
    }
}



OK
[Download]

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Posted by Anita at December 24, 2013 - 5:35 PM