MainPage.xaml.cs 1.96 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
using LibVLCSharp.Forms.Shared;
using LibVLCSharp.Shared;
using System.Diagnostics;
using Xamarin.Forms;

namespace ForegroundBackground
{
    public partial class MainPage : ContentPage
    {
        LibVLC _libVLC;
        MediaPlayer _mediaPlayer;
        VideoView _videoView;
        float _position;

        public MainPage()
        {
            InitializeComponent();

19
            MessagingCenter.Subscribe<string>(this, "OnPause", app =>
20
            {
21
                VideoView.MediaPlayerChanged -= MediaPlayerChanged;
22
                _mediaPlayer.Pause();
23 24 25 26 27 28 29 30 31 32 33
                _position = _mediaPlayer.Position;
                _mediaPlayer.Stop();
                MainGrid.Children.Clear();
                Debug.WriteLine($"saving mediaplayer position {_position}");
            });

            MessagingCenter.Subscribe<string>(this, "OnRestart", app =>
            {
                _videoView = new VideoView { HorizontalOptions = LayoutOptions.FillAndExpand, VerticalOptions = LayoutOptions.FillAndExpand };
                MainGrid.Children.Add(_videoView);

34
                _videoView.MediaPlayerChanged += MediaPlayerChanged;
35 36 37

                _videoView.MediaPlayer = _mediaPlayer;
                _videoView.MediaPlayer.Position = _position;
38
                _position = 0;
39 40 41 42 43 44 45
            });
        }

        protected override void OnAppearing()
        {
            base.OnAppearing();

46
            VideoView.MediaPlayerChanged += MediaPlayerChanged;
47 48 49 50 51 52 53

            Core.Initialize();

            _libVLC = new LibVLC();
            _mediaPlayer = new MediaPlayer(_libVLC)
            {
                Media = new Media(_libVLC,
Martin Finkel's avatar
Martin Finkel committed
54
                "https://download.blender.org/peach/bigbuckbunny_movies/BigBuckBunny_320x180.mp4",
55
                FromType.FromLocation)
56 57 58 59 60
            };

            VideoView.MediaPlayer = _mediaPlayer;
        }

61
        private void MediaPlayerChanged(object sender, System.EventArgs e)
62 63 64 65 66
        {
            _mediaPlayer.Play();
        }
    }
}