Tom Xue
Tom Xue

Reputation: 3355

How to clear MediaPlayer's cache in an UWP application?

In my UWP application, I have a MediaPlayer. When switch its source, I find that the previous video has some residual fragment. To solve this issue, a solution is to clear the MediaPlayer's cache when switching. But I did not find this kind of interface.

More

I make a demo with below GitHub link. I used Nico's suggestion to call MediaSource's Dispose() function. But as you could see, when switch between MainPage and VideoPage1, the video residual fragment issue still exists.

More 2

I paste my code as below. The test should be done via switching between MainPage and VideoPage1, back and forth. Then you could see the video residual fragment phenomenon.

But as I comment out, if we set the Source twice, then the vide residual fragment phenomenon does not exist, why?

Any other official solution?

mMediaPlayer.Source = ms;
mMediaPlayer.Source = ms;

Test code:

public sealed partial class VideoPage1 : Page
{
    MediaPlayer mMediaPlayer;
    MediaSource ms;
    public static int count;

    public VideoPage1()
    {
        this.InitializeComponent();
        NavigationCacheMode = NavigationCacheMode.Enabled;

        mMediaPlayer = new MediaPlayer();
    }

    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        count++;

        if (count % 2 == 0)
            ms = MediaSource.CreateFromUri(new Uri("ms-appx:///Assets/1.mp4"));
        else
            ms = MediaSource.CreateFromUri(new Uri("ms-appx:///Assets/2.mp4"));

        // One solution: if we set Source twice, then 
        // the vide residual fragment phenomenon does not exist, but why?
        // mMediaPlayer.Source = ms;
        mMediaPlayer.Source = ms;
        mMediaPlayer.Play();

        VideoObj.SetMediaPlayer(mMediaPlayer);
    }

    protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
    {
        mMediaPlayer.Pause();
        ms.Dispose();
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        Frame rootFrame = Window.Current.Content as Frame;
        rootFrame.Navigate(typeof(MainPage));
    }
}

https://github.com/tomxue/Video_residual_fragment_issue

Upvotes: 1

Views: 204

Answers (2)

nima amr
nima amr

Reputation: 661

For clearing medial players, you should clear ResourceByteRangeOffset and ResourceByteRangeLength from args this document help you Adaptive streaming

Upvotes: 0

Nico Zhu
Nico Zhu

Reputation: 32775

How to clear MediaPlayer's cache in an UWP application?

Please check this document. MediaSource contains Dispose that use to releasing, or resetting unmanaged resources. Before you switch to another source please invoke it manually. it will clear previous video's residual fragment.

Upvotes: 1

Related Questions