Search code examples
xamarin.formslibvlcsharp

I have a very strange question with xamarin.form and libvlcsharp


When I create LibVLC and MediaPlayer objects in the constructor and play the video, there is only sound but no image. When I create LibVLC and MediaPlayer objects in the'Play' function, there are sounds and images. I don't want to create a MediaPlayer object every time the play function is called. what should I do?

using System;
using System.ComponentModel;
using System.Windows.Input;
using LibVLCSharp.Shared;
using static Xamarin.Essentials.Permissions;


namespace MediaElement
{
    /// <summary>
    /// Represents the main viewmodel.
    /// </summary>
    public class MainViewModel : INotifyPropertyChanged
    {
        /// <summary>
        /// Property changed event
        /// </summary>
        public event PropertyChangedEventHandler PropertyChanged;


        /// <summary>
        /// Initializes a new instance of <see cref="MainViewModel"/> class.
        /// </summary>
        public MainViewModel()
        {
            Core.Initialize();
            LibVLC = new LibVLC();
            MediaPlayer = new MediaPlayer(LibVLC) { EnableHardwareDecoding = true };
        }

        
        

        private LibVLC _libVLC;
        /// <summary>
        /// Gets the <see cref="LibVLCSharp.Shared.LibVLC"/> instance.
        /// </summary>
        public LibVLC LibVLC
        {
            get => _libVLC;
            private set => Set(nameof(LibVLC), ref _libVLC, value);
        }

        private MediaPlayer _mediaPlayer;
        /// <summary>
        /// Gets the <see cref="LibVLCSharp.Shared.MediaPlayer"/> instance.
        /// </summary>
        public MediaPlayer MediaPlayer
        {
            get => _mediaPlayer;
            private set => Set(nameof(MediaPlayer), ref _mediaPlayer, value);
        }

               

        /// <summary>
        /// Initialize LibVLC and playback when page appears
        /// </summary>
        public void Play(String path)
        {
                MediaPlayer.Play(new LibVLCSharp.Shared.Media(LibVLC, new Uri(path)));             
        }

        

        private void Set<T>(string propertyName, ref T field, T value)
        {
            if (field == null && value != null || field != null && !field.Equals(value))
            {
                field = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
            }
        }

    }
}

Solution

  • You only sent half of your code, we don't know how you are using your VideoView control.

    As a general rule of thumb:

    • How do you attach the MediaPlayer to your view?
    • Do you properly wait for the view to be visible before calling Play?
    • Have a look at the samples here and compare to see what you did wrong.