Introduction
I once needed to create thumbnails of videos to be used in a WPF application. First, I thought of using FFMPEG to get the job done, but then changed my mind and used System.Windows.Media.MediaPlayer
after doing some search on the Internet.
I owe thanks to all the people from different places on the Internet from whom I derived this version of my application. I do not remember the places from where I had taken the code snippets. But I am thankful to all of them anyway!
To make things more interesting, the sample code creates thumbnails using multi-threading. We also show a nice animation while the thumbnail creation process is in progress.
MediaElement
is a bit sluggish and takes some time before the video is loaded and we have to wait a little before acquiring the thumbnail. Unfortunately, the time to wait is quite arbitrary and varies from machine to machine and invocation to invocation. So I have provided a combo-box to change the wait time if the default does not work. I have also provided another combo-box to select the position in seconds from the start of the video to specify the time when the screenshot should be taken.
Here is a screenshot of the sample application at work:
The Code
Following is a simplified version of the accompanying sample application. I have placed comments where needed. The sample application is multi-threaded and uses just a little more elaborate code. Please see the sample code for more details.
void ImportMedia(string mediaFile, int waitTime, int position)
{
MediaPlayer player = new MediaPlayer { Volume = 0, ScrubbingEnabled = true };
player.Open(new Uri(mediaFile));
player.Pause();
player.Position = TimeSpan.FromSeconds(position);
System.Threading.Thread.Sleep(waitTime * 1000);
RenderTargetBitmap rtb = new RenderTargetBitmap(120, 90, 96, 96, PixelFormats.Pbgra32);
DrawingVisual dv = new DrawingVisual();
using (DrawingContext dc = dv.RenderOpen())
{
dc.DrawVideo(player, new Rect(0, 0, 120, 90));
}
rtb.Render(dv);
Duration duration = player.NaturalDuration;
int videoLength = 0;
if (duration.HasTimeSpan)
{
videoLength = (int)duration.TimeSpan.TotalSeconds;
}
BitmapFrame frame = BitmapFrame.Create(rtb).GetCurrentValueAsFrozen() as BitmapFrame;
BitmapEncoder encoder = new JpegBitmapEncoder();
encoder.Frames.Add(frame as BitmapFrame);
MemoryStream memoryStream = new MemoryStream();
encoder.Save(memoryStream);
player.Close();
}