码迷,mamicode.com
首页 > Windows程序 > 详细

win8 metro 自己写摄像头录像项目

时间:2017-07-16 13:37:28      阅读:274      评论:0      收藏:0      [点我收藏+]

标签:hand   mode   alt   row   点击   orm   bytes   specified   efi   

这是要求不适用CameraCaptureUI等使用系统自带的 camera  UI界面。要求我们自己写调用摄像头摄像的方法,如今我把我的程序贴下:


UI界面的程序:

<Page
    x:Class="Camera3.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://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="调用摄像头" HorizontalAlignment="Left" Margin="295,83,0,0" VerticalAlignment="Top" Click="btnCamera_Click"/>
        <Button x:Name="btnSettings" Content="摄像头设置" HorizontalAlignment="Left" Margin="482,83,0,0" VerticalAlignment="Top"/>
        <Button x:Name="btnVideo" Content="拍摄视频" HorizontalAlignment="Left" Margin="685,83,0,0" VerticalAlignment="Top" Click="btnVideo_Click"/>
        <Button x:Name="btnSave" Content="保存视频" HorizontalAlignment="Left" Margin="867,83,0,0" VerticalAlignment="Top" Click="btnSave_Click"/>
        <GridView HorizontalAlignment="Left" Margin="246,200,0,0" VerticalAlignment="Top" Width="800" Height="600">
            <CaptureElement x:Name="capture1" Height="600" Width="800"/>
        </GridView>

    </Grid>
</Page>


主程序里的代码:

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=234238

namespace Camera3
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within 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)
                    {

                        capture1.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.GenerateUniqueName);
                await mediaVideo.StartRecordToStorageFileAsync(videoProfile, video);
            }
            
        }

        private async void btnSave_Click(object sender, RoutedEventArgs e)
        {
            if (video != null)
            {
                FileSavePicker videoPicker = new FileSavePicker();
                videoPicker.CommitButtonText = "保存视频";
                videoPicker.SuggestedFileName = "hello";
                videoPicker.FileTypeChoices.Add("视频", 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);
                }

            }
        }
             //将图片写入到缓冲区  
        private IBuffer RandomAccessStreamToBuffer(IRandomAccessStream randomstream)
        {
            Stream stream = WindowsRuntimeStreamExtensions.AsStreamForRead(randomstream.GetInputStreamAt(0));
            MemoryStream memoryStream = new MemoryStream();
            IBuffer buffer = null;
            if (stream != null)
            {
                byte[] bytes = ConvertStreamTobyte(stream);  //将流转化为字节型数组  
                if (bytes != null)
                {
                    var binaryWriter = new BinaryWriter(memoryStream);
                    binaryWriter.Write(bytes);
                }
            }
          
            buffer = WindowsRuntimeBufferExtensions.GetWindowsRuntimeBuffer(memoryStream, 0, (int)memoryStream.Length);
           
            return buffer;    
        }

        //将流转换成二进制  
        public static byte[] ConvertStreamTobyte(Stream input)
        {
            byte[] buffer = new 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();
            }
        }
        
    }
}

可是这里出现了一个问题,不知道怎么解决。

之所以放上来。希望有大牛能够帮我解决一下,看看究竟是出现了什么问题:

这是执行的界面。点击“调用摄像头”。能够调用摄像头:

技术分享

会发现上面的界面已经调用了摄像头,这一个模块式没有什么问题的。


可是问题出如今以下,以下我点击“拍摄视频”的button。出现例如以下异常:

技术分享


以下我把我捕获的异常给大家看看:

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()

上面就是捕获的异常情况。能够从异常的截图上发现,出现异常的代码可能是:
public async void btnVideo_Click(object sender, RoutedEventArgs e)
        {
            if (mediaVideo != null)
            {
                video = await KnownFolders.VideosLibrary.CreateFileAsync("some.mp4", CreationCollisionOption.GenerateUniqueName);
                <span style="color:#ff0000;">await mediaVideo.StartRecordToStorageFileAsync(videoProfile, video);</span>
            }
            
        }

应该就是标记为红色的那部分代码,以下我对它进行断点调试:

技术分享

技术分享

上面两幅断点调试的图片能够看出这

<span style="color:#ff0000;">StartRecordToStorageFileAsync(videoProfile, video)</span>
这个函数的两个參数均没有出现故障,參数的传递的正确的。如今怎么会出现这种情况。

 希望知道的同学能够给我答案。告诉我为什么,等待您的回复,谢谢同志们。


PS:搞了一下午,最终发现了这个程序的问题。如今把正确的程序源码传上去。

以下是我的程序源码,希望打啊多多指正。

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


win8 metro 自己写摄像头录像项目

标签:hand   mode   alt   row   点击   orm   bytes   specified   efi   

原文地址:http://www.cnblogs.com/brucemengbm/p/7190176.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!