Search code examples
c#xamarin.formsandroid-mediaplayerandroid-videoview

Video player in Xamarin Forms is gone when minimized and resumed


I have implemented a video player in xamarin forms to play as a background video for my login screen. The video successfully loads at start and plays without sound and loops(as configured). But the problem is when I minimize the app and resume again, then the video is gone and I can't even play it back like video.play if paused or stopped

The links I tried are as follows

  1. http://makanda.io/how-to-create-a-background-video-in-xamarin-forms/ (I tried this link first)
  2. https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/custom-renderer/video-player/ (then completely replaced with this)

Both links work as desired except the issue which is the same in both links.

What I have tried to solve the issue?

  1. I tried resuming the video as if(videoPlayer.Status == Renderers.VideoStatus.Paused) videoPlayer.Play() inside my OnAppearing() method. But it doesn't work
  2. I am currently trying to dynamically load the video from code behind inside a stack layout. But I don't know how to set the video source from code behind. I am doing it as follows

string source = "";
switch (Device.RuntimePlatform)
{
    case Device.iOS:
        source = "Videos/walkthroughvideo9_16.mp4";
        break;
    case Device.Android:
        source = "walkthroughvideo9_16.mp4";
        break;
    default:
        source = "walkthroughvideo9_16.mp4";
        break;
}

VideoPlayer video = new VideoPlayer()
{
    Source = (UriVideoSource)source
};

An error says, cannot convert string to UriVideoSource

AN HELP LINK:

https://developer.android.com/reference/android/widget/VideoView

Seems like the video view does not maintain its state when the app goes into the background.


Solution

  • I used a timer as a workaround to resume the video which pauses when the app goes into sleep mode.

    protected override void OnAppearing()
    {
        base.OnAppearing();
        shouldTimerRun = true;
    
        Device.StartTimer(new TimeSpan(0, 0, 1), () =>
        {
            Device.BeginInvokeOnMainThread(() =>
            {
                if (videoPlayer.Status == VideoStatus.Paused)
                {
                    //videoPlayer.TimeToEnd = timeSpan;
                    videoPlayer.Position = timeSpan;
                    videoPlayer.Play();
                }
            });
            return shouldTimerRun;
        });
    }
    
    protected override void OnDisappearing()
    {
        base.OnDisappearing();
        shouldTimerRun = false;
        timeSpan = videoPlayer.Position;
    }