Silverlight 4:从默认摄像头捕获视频






4.57/5 (10投票s)
微软于2009年11月18日发布了Silverlight 4 Beta 1。 在新的功能中,我将演示其中一项功能“使用Silverlight 4访问默认摄像头”。
引言
微软于2009年11月18日发布了Silverlight 4 Beta 1。 新版本带来许多改进。 其中大部分是Silverlight开发者和用户要求的。 在本文中,我将演示一项新功能“使用Silverlight 4访问默认摄像头”。
背景
要创建一个Silverlight 4应用程序,您需要“Visual Studio 2010 Beta 2”。 从微软网站下载它。 然后安装“Visual Studio 2010 Beta 2的Silverlight Tools 4”。 成功安装后,创建一个Silverlight 4应用程序项目。
感兴趣的代码
完成项目创建后,Visual Studio将为您打开MainPage.xaml。 在Grid中添加一个Rectangle和三个Button。 Rectangle将负责来自您的VideoCaptureDevice
的视频输出,按钮将负责与设备的交互。 添加完成后,您的XAML将如下所示
<Grid x:Name="LayoutRoot" Background="White">
<StackPanel HorizontalAlignment="Center">
<Rectangle x:Name="rectWebCamView" Width="500" Height="400"/>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
<Button x:Name="btnCaptureDevice"
Content="Capture Device" Margin="5"/>
<Button x:Name="btnPlayCapture"
Content="Start Capture" Margin="5"/>
<Button x:Name="btnStopCapture"
Content="Stop Capture" Margin="5"/>
</StackPanel>
</StackPanel>
</Grid>
现在,转到代码隐藏文件(MainPage.xaml.cs)并创建一个CaptureSource
的实例。 然后调用TryCaptureDevice()
来启动视频捕获。 这首先获取默认的视频捕获设备,并将其分配给rectangle的VideoBrush
实例。 请记住,这将要求用户授予设备权限,只有成功后才会启动设备。
private void TryCaptureDevice()
{
// Get the default video capture device
VideoCaptureDevice videoCaptureDevice =
CaptureDeviceConfiguration.GetDefaultVideoCaptureDevice();
if (videoCaptureDevice == null)
{
// Default video capture device is not setup
btnPlayCapture.IsEnabled = false;
btnStopCapture.IsEnabled = false;
btnCaptureDevice.IsEnabled = true;
MessageBox.Show("You don't have any default capture device");
}
else
{
btnPlayCapture.IsEnabled = false;
btnStopCapture.IsEnabled = false;
// Set the Capture Source to the VideoBrush of the rectangle
VideoBrush videoBrush = new VideoBrush();
videoBrush.SetSource(captureSource);
rectWebCamView.Fill = videoBrush;
// Check if the Silverlight already has access
// to the device or grant access from the user
if (CaptureDeviceConfiguration.AllowedDeviceAccess ||
CaptureDeviceConfiguration.RequestDeviceAccess())
{
btnPlayCapture.IsEnabled = true;
btnStopCapture.IsEnabled = false;
btnCaptureDevice.IsEnabled = false;
}
}
}
历史
- 2009 年 11 月 20 日:初始发布