Win8 Metro to write its own webcam video project

Source: Internet
Author: User
Tags blank page

This is a camera UI interface that requires the use of systems that do not apply to Cameracaptureui. Asking us to write our own method of invoking the camera, now I'm pasting my program:


UI interface of the program:

<page x:class= "Camera3.mainpage" xmlns= "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x= "HT Tp://schemas.microsoft.com/winfx/2006/xaml "xmlns:local=" Using:camera3 "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}" > <button x:name= "Btncamera" content= "Call camera" horizontalalignment= "left" margin= "295,83,0,0" verticalalignment= "Top" click= "Btncamera_click"/ > <button x:name= "btnsettings" content= "Camera Settings" horizontalalignment= "left" margin= "482,83,0,0" Verticalalignme nt= "Top"/> <button x:name= "Btnvideo" content= "shoot video" horizontalalignment= "left" margin= "685,83,0,0" VerticalAl Ignment= "Top" click= "Btnvideo_click"/> <button x:name= "btnsave" content= "Save Video" horizontalalignment= "left" Mar Gin= "867,83,0,0" verticalalignment= "Top" click= "Btnsave_click"/> <gridview horizontalalignment= "left" margin= "246,200,0,0" verticalalignment= "Top" Width= "8 XX "height=" > <captureelement x:name= "capture1" height= "" "Width=" ""/> </gridview&gt    ; </Grid></Page>


The code in the main program:

Using system;using system.collections.generic;using system.io;using system.linq;using System.runtime.interopservices.windowsruntime;using windows.foundation;using Windows.Foundation.Collections; Using windows.ui.xaml;using windows.ui.xaml.controls;using windows.ui.xaml.controls.primitives;using Windows.ui.xaml.data;using windows.ui.xaml.input;using windows.ui.xaml.media;using Windows.UI.Xaml.Navigation; Using windows.media.capture;using windows.storage;using windows.storage.pickers;using Windows.Devices.Enumeration; Using windows.media.mediaproperties;using windows.ui.xaml.media.imaging;using windows.ui.xaml.media;using Windows.storage.streams;using windows.media.devices;using system.threading.tasks;//The Blank Page item template is Documented at http://go.microsoft.com/fwlink/? Linkid=234238namespace camera3{//<summary>//An empty page so can be used on it own or navigated to WI    Thin a Frame.  </summary> public sealed partial class Mainpage:page {      Private MediaCapture mediavideo = null;        Private Istoragefile video = null;        Private Mediaencodingprofile videoprofile = null; Public MainPage () {this.        InitializeComponent ();                } public async void Btncamera_click (object sender, RoutedEventArgs e) {try {                Deviceinformationcollection devices = await deviceinformation.findallasync (deviceclass.videocapture); if (Devices. Count > 0) {if (Mediavideo = = null) {CAPT Ure1.                        Source = await Initialize ();                    await Mediavideo.startpreviewasync ();            }}} catch (Exception msg) {mediavideo = null; }} public Async task<mediacapture> Initialize () {mediavideo = new MediaCapture ()            ; Await Mediavideo.initialiZeasync ();            MediaVideo.VideoDeviceController.PrimaryUse = Captureuse.video;            Videoprofile = Mediaencodingprofile.createmp4 (Videoencodingquality.auto);        return mediavideo;            } public async void Btnvideo_click (object sender, RoutedEventArgs e) {if (Mediavideo! = null) {video = await KnownFolders.VideosLibrary.CreateFileAsync ("Some.mp4", Creationcollisionoption.gen                Erateuniquename);            Await Mediavideo.startrecordtostoragefileasync (videoprofile, video); }} private Async void Btnsave_click (object sender, RoutedEventArgs e) {if (V                Ideo! = null) {Filesavepicker videopicker = new Filesavepicker ();                Videopicker.commitbuttontext = "Save Video";                Videopicker.suggestedfilename = "Hello";       VIDEOPICKER.FILETYPECHOICES.ADD ("video", new string[] {". mp4", ". mpg", ". rmvb", ". mkv"});         Videopicker.suggestedstartlocation = pickerlocationid.videoslibrary;                Istoragefile videofile = await videopicker.picksavefileasync (); if (videofile! = null) {var streamrandom = await video.                    OpenAsync (Fileaccessmode.read);                    IBuffer buffer = Randomaccessstreamtobuffer (streamrandom);                Await Fileio.writebufferasync (videofile, buffer); }}}//write picture to buffer private IBuffer randomaccessstreamtobuffer (Irandomaccessstream RA Ndomstream) {Stream stream = Windowsruntimestreamextensions.asstreamforread (randomstream.            Getinputstreamat (0));            MemoryStream MemoryStream = new MemoryStream ();            IBuffer buffer = null;  if (stream! = null) {byte[] bytes = Convertstreamtobyte (stream); Will flow to byte array if (bytes! = null) {var binaryWriter = new BinaryWriter (MemoryStream);                BinaryWriter.Write (bytes); }} buffer = Windowsruntimebufferextensions.getwindowsruntimebuffer (MemoryStream, 0, (int)                       Memorystream.length);            return buffer; }//Change the flow to binary public static byte[] Convertstreamtobyte (Stream input) {byte[] buffer = NE            W byte[1024 * 1024];                using (MemoryStream ms = new MemoryStream ()) {int read; while (read = input. Read (buffer, 0, buffer. Length)) > 0) {Ms.                Write (buffer, 0, read); } return Ms.            ToArray (); }        }            }}

But there is a problem here, do not know how to solve.

The reason is put up. I hope that Daniel can help me solve it, and see what the problem is:

This is the interface for execution. Click on "Call Camera". Ability to call the camera:

Will find that the above interface has called the camera, this module is not a problem.


But the problem is below now, I click on the button "shoot video" below. An exception such as the following occurs:


Let me show you the exceptions I caught:

System.Exception:The specified object or value does not exist. Mediastreamtype at   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (Task Task)   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (Task Task) at   System.Runtime.CompilerServices.TaskAwaiter.GetResult () at   Camera3.mainpage.<btnvideo_click>d__9. MoveNext ()

The above is the catch exception condition. Can be found from the exception, the code of the exception may be:
Public async void Btnvideo_click (object sender, RoutedEventArgs e)        {            if (mediavideo! = null)            {                video = AW Ait KnownFolders.VideosLibrary.CreateFileAsync ("Some.mp4", creationcollisionoption.generateuniquename);                <span style= "color: #ff0000;" >await Mediavideo.startrecordtostoragefileasync (videoprofile, video);</span>            }                    }

It should be the part of the code marked red, and here I'll debug it for breakpoints:


watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvbgl0awfucgvuz2hhage=/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma== /dissolve/70/gravity/center ">

The above two breakpoint debugging pictures can see this

<span style= "color: #ff0000;" >startrecordtostoragefileasync (Videoprofile, video) </span>
The two parameters of this function are not faulted and the parameters are passed correctly. How can this happen now?

Students who want to know can give me the answer. Tell me why, wait for your reply, thank you comrades.


PS: After an afternoon, I finally found out the problem with this program. Now the correct program source code to pass up.

The following is my program source code, hope to play ah more correct.

http://download.csdn.net/detail/litianpeng1991/7556273


Win8 Metro to write its own webcam video project

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.