Home > Net >  Xamarin Forms MediaElement: Playing video selected from gallery with CrossMedia plugin
Xamarin Forms MediaElement: Playing video selected from gallery with CrossMedia plugin

Time:03-24

I'm trying to use the MediaElement to play a video selected from the Gallery. The path to the Video is saved within the app then bound to the MediaElement Source.

<xct:MediaElement Source="{Binding VideoUri, Converter={StaticResource VideoSourceConverter}}" 
                          AutoPlay="False"
                          ShowsPlaybackControls="True" 
                          Aspect="AspectFit"
                          HorizontalOptions="FillAndExpand" 
                          VerticalOptions="FillAndExpand" />

I'm using a converter as described in the documentation:

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
    if (value == null) return null;

    if (string.IsNullOrWhiteSpace(value.ToString()))
        return null;

    if (value.ToString().StartsWith("http"))
        return value;

    return new Uri($"ms-appdata:///{value}");
}

https://docs.microsoft.com/en-gb/xamarin/community-toolkit/views/mediaelement#play-local-media

But am getting the error: Invalid UriParameter name: Source

The saved path on Android is:

"/storage/emulated/0/Android/data/[app identifier]/files/Movies/temp/[filename].mp4"

Haven't tested in iOS yet.

Any guidance will be much appreciated.

Thanks.

CodePudding user response:

You dont need the converter just return the path to the mediaplayer control .

mediaFile = await this._mediaPicker.PickVideoAsync();
VideoUri = mediaFile.Path;

CodePudding user response:

The Converter you used is used for the UWP. UWP could play media files that are located in the app's xxxx folder by prefixing the media file with ms-appdata:///xxxx/.

For mobile devices, when you use the CrossMedia to select the video, you could get the stream directly from the file.

I use a button to do the select operation and then use the INotifyPropertyChanged to update the binding. Here is the code for your reference.

Xaml:

 <Button Clicked="Button_Clicked" Text="Select"/>
        <xct:MediaElement Source="{Binding VideoUri}" 
                      AutoPlay="False"
                      ShowsPlaybackControls="True" 
                      Aspect="AspectFit"
                      HorizontalOptions="FillAndExpand" 
                      VerticalOptions="FillAndExpand" />

Code:

 public partial class Page29 : ContentPage
{
    Page29ViewModel viewModel = new Page29ViewModel();
    public Page29()
    {
        InitializeComponent();
        this.BindingContext = viewModel;
    }

    private async void Button_Clicked(object sender, EventArgs e)
    {
        string path = string.Empty;

        MediaFile video = null;
        if (CrossMedia.Current.IsPickVideoSupported)
        {
            video = await CrossMedia.Current.PickVideoAsync();

        }

        var fileName = "sample";
        var newFile = Path.Combine(FileSystem.AppDataDirectory, fileName   ".mp4");

        if (!File.Exists(newFile))
        {
            using (var inputStream = video.GetStream())
            {
                using (FileStream outputStream = File.Create(newFile))
                {
                    await inputStream.CopyToAsync(outputStream);
                }
            }
        }
        viewModel.VideoUri = newFile;
    }
}
public class Page29ViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
    private string _videoUri;
    public string VideoUri
    {
        get { return _videoUri; }
        set { _videoUri = value; NotifyPropertyChanged(nameof(VideoUri)); }
    }
    public Page29ViewModel()
    {

    }
}
  • Related