我正在尝试使用MediaElement播放从Gallery中选择的视频。视频的路径保存在应用程序中,然后绑定到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-本地媒体
但是我得到错误:无效的UriParameter名称:源
Android上保存的路径是:
"storage/amulated/0/Android/data/[app identifier]/files/Movies/temp/[filename].mp4";
尚未在iOS中进行测试。
任何指导都将不胜感激。
谢谢。
您使用的转换器用于UWP。UWP可以播放位于应用程序xxxx文件夹中的媒体文件,方法是在媒体文件前面加上ms-appdata:///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()
{
}
}
您不需要转换器,只需返回到mediaplayer控件的路径即可。
mediaFile = await this._mediaPicker.PickVideoAsync();
VideoUri = mediaFile.Path;