gpt4 book ai didi

c# - 如何在 Xamarin.Forms 中获取嵌入文件的 URL/路径

转载 作者:太空宇宙 更新时间:2023-11-03 12:10:19 24 4
gpt4 key购买 nike

我无法访问 Xamarin.Forms 项目中嵌入的 .mp4 文件。根据File Handling in Xamarin.Forms文档,它说,

The path of the file on each platform can be determined from a .NET Standard library by using a value of the Environment.SpecialFolder enumeration as the first argument to the Environment.GetFolderPath method. This can then be combined with a filename with the Path.Combine method.

我还按照页面上的说明进行操作,该页面告诉您确保将文件的“Build Action”设置为“EmbeddedResource”。最终我试图获取文件的路径/url,以便我可以将它传递给 MediaManagerCrossMediaManager.Current.Play() 函数。这是一些不断失败的代码,无论我如何调整它。其中大部分直接取自上面链接的 Xamarin 文档:

// Gets the path to the video file.
string fileDirectory = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
string file = "Signing.video.banana.mp4";
string pathToFile = Path.Combine(fileDirectory, file);

// Print some info about the file and its directory
System.Diagnostics.Debug.WriteLine(pathToFile);
System.Diagnostics.Debug.WriteLine(File.Exists(pathToFile));

.mp4 文件位于名为“video”的文件夹中,该文件夹直接位于“Signing”项目中。我试过调整文件路径,让它只是文件,只是文件和视频文件夹,我试过使用“/”而不是“。”来分隔目录。我总是得到的打印输出是该文件不存在。在 iOS 模拟器上运行时,打印的路径总是看起来像这样:

/Users/doug/Library/Developer/CoreSimulator/Devices/FD9E9045-EF6A-4ECA-9192-25CEC0E7C23C/data/Containers/Data/Application/AF92806E-C68F-45ED-814D-C383821F470A/Documents/Signing.video.banana.mp4

我看到过建议将“file://”附加到文件路径的前面,以及其他类似的建议。什么都不管用。如何在 Xamarin.Forms 中嵌入文件并稍后检索其文件路径?

最佳答案

您需要将程序集嵌入资源复制到临时文件,以便 MediaManager 播放它。

使用 Xamarin.Essentials,您可以获得操作系统的缓存目录,然后将资源复制到其中并通过 file:// url 播放。

示例:

var cacheFile = Path.Combine(FileSystem.CacheDirectory, "cached.mp4");
if (File.Exists(cacheFile))
File.Delete(cacheFile);
using (var resource = Assembly.GetExecutingAssembly().GetManifestResourceStream("YourFullEmbeddedResourceResourceID.mp4"))
using (var file = new FileStream(cacheFile, FileMode.Create, FileAccess.Write))
{
resource.CopyTo(file);
}
await CrossMediaManager.Current.Play(new MediaFile("file://localhost/" + cacheFile, MediaFileType.Video, ResourceAvailability.Local));

注意:我个人不会使用嵌入式资源,因为它们会使您的程序集(或 native 库中的 .text 段)膨胀,从而消耗应用程序内存,导致加载时间变慢等,但使用基于 native 包/ Assets 的文件并将它们复制到缓存目录。您可以使用 Xamarin.Essentials 通过 OpenAppPackageFileAsync 获取那些只读的 bundle/ Assets 文件,并使用该流将文件复制到缓存目录。

关于c# - 如何在 Xamarin.Forms 中获取嵌入文件的 URL/路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52635317/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com