使用MediaCapture的摄像机流过一段时间后会停止工作吗?

时间:2018-07-10 21:06:20

标签: c# wpf uwp windows-10

我正在使用Windows.Media.Capture.MediaCapture从Surface网络摄像头获取视频流,并将其显示在屏幕上。

await _mediaCap.InitializeAsync(new MediaCaptureInitializationSettings
{
    VideoDeviceId = devices?.FirstOrDefault()?.Id,
    StreamingCaptureMode = StreamingCaptureMode.Video,
    PhotoCaptureSource = PhotoCaptureSource.VideoPreview
});

await _mediaCap.VideoDeviceController.SetMediaStreamPropertiesAsync(
    MediaStreamType.VideoPreview, encodeProps);

_dRequest = new DisplayRequest();
_dRequest.RequestActive();

我定期使用以下方法从相机流中抓取一帧:

using (var randomAccessStream = new InMemoryRandomAccessStream())
{
    await Application.Current.Dispatcher.Invoke(async () =>
    {
        await _mediaCap.CapturePhotoToStreamAsync(properties, randomAccessStream);
    });

    await Task.Run(() => 
    { 
         randomAccessStream.Seek(0);
         using (var ioStream = randomAccessStream.AsStream())
         {
             BitmapImage bitmapImage = new BitmapImage();
             bitmapImage.BeginInit();
             bitmapImage.StreamSource = ioStream;
             bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
             bitmapImage.EndInit();
             bitmapImage.Freeze();

             capturedImage = bitmapImage;
         }
     });
}

一段时间后,流失败,并出现以下异常:

"The request is invalid in the current state. Started"

Similar questions对此建议确保确保调用CapturePhotoToStreamAsync的线程是UI线程(如上所示),但是问题仍然存在。从发生前的时间来看,这似乎是半随机的,在发生前20分钟到几个小时之间。

请注意,这是WPF应用程序(.NET 4.6.2),using WinRT是用于利用MediaCapture类的。

1 个答案:

答案 0 :(得分:0)

对于我而言,按顺序跟踪故障数量非常有价值,如果达到某个阈值,则请处置相机并重置取决于相机的控件。

  • 调用StopAsync()对象上的CapturePreview
  • Dispose()对象上调用MediaCapture

我发现,在经常被拆除和重建的视图中控制摄像机预览Image的稳定性远不如将其保持在“ MainView”中并保持其活动状态(如果它开始出现上述类似的垃圾邮件错误)那样稳定,则使用相同的Image来重建相机)。

其他注意事项:

  • 请注意哪些线程正在处理各种事情。自然,您将需要UI线程来管理Image控件
  • 使用SemaphoreSlim对象在确保不会同时建造,处置或捕获摄像机的过程中非常有用。
相关问题