Search code examples
c#windows-8microsoft-metrowindows-runtimemediaelement

How to change the position of a video using MediaElement in Windows8?


Currently I am doing this in my code,

 playbackElement1.AutoPlay = true;
 playbackElement1.SetSource(stream, this.m_recordStorageFile.FileType);
 playbackElement1.Position = new TimeSpan(0, 0, 0, 0, 5000);
 playbackElement1.Play();

It doesn't work, checking for a video longer than 5 secs.


Solution

  • There are two problems. First, MediaElement can only set the position once the media is loaded, determined by handling the MediaOpened event. Secondly, not all media is seekable. Check by calling CanSeek. Use something like:

    playbackElement1.AutoPlay = true;
    // Will fire after the media has loaded
    playbackElement1.MediaOpened += (source, args) =>
    {
        MediaElement player = (MediaElement) source;
        if (player.CanSeek)
        {
            player.Position = new TimeSpan(0, 0, 0, 0, 5000);   
        }
    }                     
    playbackElement1.SetSource(stream, this.m_recordStorageFile.FileType);
    

    Once loaded, use the NaturalDuration property to see the length of the media, converting it to a TimeSpan using HasTimeSpan and TimeSpan properties if needed.