上一篇文章介绍了在win8 metro 调用摄像头拍摄照片并将照片保存在相应的位置的功能,那么这一片文章主要介绍了的就是录制视频了,其实这个差不多,所用的思想也是一样的,因为图片和视频都可以转化为流文件,那么它们本质上都是一样的,但是还是有个别地方时不同的,接下来我们就介绍一下这个别地方的不同吧
下面是metro UI的代码:
下面是UI的控制代码:
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.UI.Xaml.Media.Imaging;
using Windows.Storage;
using Windows.Storage.Streams;
using Windows.Storage.Pickers;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
namespace Camera1
{
///
/// An empty page that can be used on its own or navigated to within a Frame.
///
public sealed partial class MainPage : Page
{
private StorageFile file = null;
public MainPage()
{
this.InitializeComponent();
}
private async void btnCamera_Click(object sender, RoutedEventArgs e)
{
CameraCaptureUI dialog = new CameraCaptureUI();
dialog.VideoSettings.Format = CameraCaptureUIVideoFormat.Mp4;
file = await dialog.CaptureFileAsync(CameraCaptureUIMode.Video);
if (file != null)
{
IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.Read);
media.SetSource(fileStream,file.ContentType);
}
}
private async void btnSave_Click(object sender, RoutedEventArgs e)
{
FileSavePicker picker = new FileSavePicker();
picker.CommitButtonText = "保存";
picker.SuggestedFileName = "hello";
picker.FileTypeChoices.Add("图片",new string[]{".mp4",".avi",".mkv",".mpg",".rmvb"});
picker.SuggestedStartLocation = PickerLocationId.VideosLibrary;
StorageFile filePath = await picker.PickSaveFileAsync();
if (filePath != null)
{
var streamRandom = await file.OpenAsync(FileAccessMode.Read);
IBuffer buffer = RandomAccessStreamToBuffer(streamRandom);
await FileIO.WriteBufferAsync(filePath, buffer);
}
}
//将视频写入到缓冲区
private IBuffer RandomAccessStreamToBuffer(IRandomAccessStream randomstream)
{
Stream stream = WindowsRuntimeStreamExtensions.AsStreamForRead(randomstream.GetInputStreamAt(0));
MemoryStream memoryStream = new MemoryStream();
if (stream != null)
{
byte[] bytes = ConvertStreamTobyte(stream);
if (bytes != null)
{
var binaryWriter = new BinaryWriter(memoryStream);
binaryWriter.Write(bytes);
}
}
IBuffer 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();
}
}
}
}