我的想法是在App启动时播放一段视频,实现方式如下:
准备一个视频: Logo.mp4
添加到资源中:Assets
然后将资源设置为 AndroidAsset
启动时,将资源文件拷贝到程序目录的files下:
protected override void OnCreate(Bundle savedInstanceState){base.OnCreate(savedInstanceState); Xamarin.Essentials.Platform.Init(this, savedInstanceState);global::Xamarin.Forms.Forms.Init(this, savedInstanceState);LoadApplication(new App());Instance = this;CopyFileToDataFolder("Logo.mp4");}/// <summary>/// 将资源拷贝到files目录/// </summary>/// <param name="fileName"></param>private void CopyFileToDataFolder(string fileName){using (var sourceFile = Assets.Open(fileName)){var destFile = Path.Combine(FilesDir.AbsolutePath, fileName);if (!File.Exists(destFile)){using (var destStream = new FileStream(destFile, FileMode.Create, FileAccess.Write)){sourceFile.CopyTo(destStream);}}}}
接着Nuget添加视频控件包:Xamarin Community Toolkit 注意兼容版本
Xamarin Community Toolkit 要求Xamarin.Forms 最低版本为5.0.0.2291 更新到这个版本即可(稳定一些,最新版本有其他兼容性问题)
在UI上添加 视频播放控件 MediaElement:
xmlns:vid="clr-namespace:Xamarin.CommunityToolkit.UI.Views;assembly=Xamarin.CommunityToolkit"<vid:MediaElementx:Name="videoPlayer"Aspect="AspectFill"AutoPlay="True"HorizontalOptions="Fill"ShowsPlaybackControls="False"VerticalOptions="Fill" />
最后,在App启动时,添加播放视频的代码
var assembly = System.Reflection.Assembly.GetExecutingAssembly();
//获取程序文件目录 即files 目录 -- Logo.mp4资源的拷贝目录
string baseUri = DependencyService.Get<ILocalIPAddress>().GetBaseDirectory();
string uri = baseUri + "/Logo.mp4";
if (System.IO.File.Exists(uri))
{//播放文件MediaSource ms = MediaSource.FromFile(uri);var videoPlayer = UIElement.FindByName<MediaElement>("videoPlayer");videoPlayer.Source = ms;videoPlayer.MediaEnded += ((object sender, EventArgs e) =>{//播放完成后的处理事件Thread.Sleep(500);});
}