You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Xamarin Forms:如何使用本地文件夹中的嵌入视频?

解决方案:Xamarin Community Toolkit MediaElement访问本地视频资源

Android 端配置与访问

  • 在Android项目的Assets文件夹下创建Videos子文件夹,放入目标视频文件(例如demo.mp4)
  • 关键设置:选中视频文件,在属性窗口将Build Action设为AndroidAsset
  • 访问路径格式:file:///android_asset/Videos/demo.mp4
  • XAML示例代码:
<xct:MediaElement Source="file:///android_asset/Videos/demo.mp4" AutoPlay="True" />

iOS 端配置与访问

  • 在iOS项目的Resources文件夹下创建Videos子文件夹,放入目标视频文件(例如demo.mp4)
  • 关键设置:选中视频文件,在属性窗口将Build Action设为BundleResource
  • XAML中直接使用相对路径示例:
<xct:MediaElement Source="Videos/demo.mp4" AutoPlay="True" />
  • 后台代码获取路径的方式:
var videoPath = NSBundle.MainBundle.PathForResource("demo", "mp4", "Videos");
mediaElement.Source = new Uri(videoPath);

关于ms-appx:///和ms-appdata:///的说明

  • ms-appx:///指向应用安装目录(对应Android的Assets、iOS的Resources这类打包时嵌入的资源),跨平台场景可统一使用该路径,前提是各平台文件结构和Build Action设置正确:
<xct:MediaElement Source="ms-appx:///Videos/demo.mp4" AutoPlay="True" />
  • ms-appdata:///指向应用私有数据目录,用于存储用户下载或生成的动态文件,并非当前场景需要的资源目录

常见注意事项

  • 优先选择各平台通用的视频格式(如MP4/H.264),避免兼容性问题
  • 必须设置正确的Build Action,否则资源不会被打包进应用
  • 跨平台开发时可通过平台判断适配路径:
string videoSource;
if (Device.RuntimePlatform == Device.Android)
{
    videoSource = "file:///android_asset/Videos/demo.mp4";
}
else if (Device.RuntimePlatform == Device.iOS)
{
    videoSource = "Videos/demo.mp4";
}
else
{
    videoSource = "ms-appx:///Videos/demo.mp4";
}
mediaElement.Source = new Uri(videoSource);

内容的提问来源于stack exchange,提问作者ThisQRequiresASpecialist

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 07:30:23