Issues with MediaPlayer and RenderTargetBitmap getting a frame image from video

203 Views Asked by At

I'm trying to use MediaPlayerto get a frame from video as an image.

MediaPlayer _mediaPlayer = new MediaPlayer();
_mediaPlayer.ScrubbingEnabled = true;
_mediaPlayer.Open(new Uri("c:\\Sample.mp4"));
_mediaPlayer.Position = new TimeSpan(0, 1, 0);
var drawingVisual = new DrawingVisual();
System.Threading.Thread.Sleep(1000);
var renderTargetBitmap = new RenderTargetBitmap(_mediaPlayer.NaturalVideoWidth, _mediaPlayer.NaturalVideoHeight, 96, 96, PixelFormats.Default);

I had to use Sleep(1000), otherwise I get an error. Is there a solution or do I have to find another way maybe better than MediaPlayer?

1

There are 1 best solutions below

0
On BEST ANSWER

When you are calling Open, the media is being opened, but depending on the size of the media this may take a certain amount of time. Accessing the media immediately or waiting for a fixed amount of time is will lead to erroneous behavior. Instead, you should subscribe to the MediaOpened event before opening the media.

_mediaPlayer.MediaOpened += OnMediaOpened;

When the MediaOpened event is fired and OnMediaOpended is called, the media is loaded and ready to interact with. In the event handler, you should go to the position and render the bitmap.

private void OnMediaOpened(object sender, EventArgs e)
{
   // ... your drawing code.
}

Please keep in mind, that loading the media can also fail. To handle this case, you can subscribe to the MediaFailed event, otherwise the bitmap will not be created and you might not be aware why.