Xamarin Forms MediaElement:使用 CrossMedia 插件播放从图库中选择的视频

发布于 2025-01-16 08:24:49 字数 1288 浏览 3 评论 0原文

我正在尝试使用 MediaElement 播放从图库中选择的视频。视频的路径保存在应用程序中,然后绑定到 MediaElement 源。

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

我正在使用文档中所述的转换器:

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://learn.microsoft.com/en-gb/xamarin/community-toolkit/views/mediaelement#play-local-media

但收到错误:无效UriParameter name: Source

Android 上的保存路径为:

“/storage/emulated/0/Android/data/[appidentifier]/files/Movies/temp/[filename].mp4”

尚未在 iOS 中进行测试。

任何指导将不胜感激。

谢谢。

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(
quot;ms-appdata:///{value}");
}

https://learn.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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

无远思近则忧 2025-01-23 08:24:49

您使用的转换器用于 UWP。 UWP 可以通过在媒体文件前加上 ms-appdata:///xxxx/ 前缀来播放位于应用的 xxxx 文件夹中的媒体文件。

对于移动设备,当您使用CrossMedia选择视频时,您可以直接从文件中获取流。

我使用按钮执行选择操作,然后使用 INotifyPropertyChanged 更新绑定。这是代码供您参考。

XAML:

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

代码:

 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()
    {

    }
}

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()
    {

    }
}
层林尽染 2025-01-23 08:24:49

您不需要转换器,只需返回媒体播放器控件的路径即可。

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

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

mediaFile = await this._mediaPicker.PickVideoAsync();
VideoUri = mediaFile.Path;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文