.NET 7 MAUI应用无法访问本地MP3物理文件求助
解决方案:.NET 7 MAUI 本地MP3播放问题
一、修复AudioManager播放失败问题
你的代码错误在于使用了FileSystem.OpenAppPackageFileAsync——这个方法仅用于读取应用安装包内的嵌入式资源,而你下载的MP3存放在应用私有数据目录,需要直接读取本地文件流:
private async void MyPlayer(string mp3FileName) { // 拼接完整路径:FileSystem.AppDataDirectory对应"/data/user/0/com.companyname.myapp/files" string fullPath = Path.Combine(FileSystem.AppDataDirectory, "Download", mp3FileName); if (!File.Exists(fullPath)) { await Shell.Current.DisplayAlert("错误", "文件不存在", "确定"); return; } // 打开本地文件流并创建播放器 using var fileStream = File.OpenRead(fullPath); var audioPlayer = AudioManager.Current.CreatePlayer(fileStream); audioPlayer.Play(); }
调用时直接传入文件名即可:MyPlayer("2012-05-06_AM1.mp3")
二、修复WebView audio标签播放失败问题
Android WebView的安全策略禁止直接访问应用私有目录的file://路径,需通过FileProvider生成content://格式的URI来访问:
步骤1:配置AndroidManifest.xml
在Android项目的AndroidManifest.xml中添加FileProvider配置:
<application ...> <provider android:name="androidx.core.content.FileProvider" android:authorities="${applicationId}.fileprovider" android:exported="false" android:grantUriPermissions="true"> <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths" /> </provider> </application>
步骤2:创建file_paths.xml
在Android项目的Resources/xml目录下新建file_paths.xml(无xml目录则手动创建):
<?xml version="1.0" encoding="utf-8"?> <paths xmlns:android="http://schemas.android.com/apk/res/android"> <!-- 映射应用files/Download目录 --> <files-path name="downloads" path="Download/" /> </paths>
步骤3:生成URI并加载HTML
在MAUI代码中生成content://URI,注入到WebView的HTML中:
string mp3FileName = "2012-05-06_AM1.mp3"; string fullPath = Path.Combine(FileSystem.AppDataDirectory, "Download", mp3FileName); FileInfo fileInfo = new FileInfo(fullPath); string audioUri = string.Empty; #if ANDROID var context = Android.App.Application.Context; // 生成content格式的URI var uri = AndroidX.Core.Content.FileProvider.GetUriForFile(context, context.PackageName + ".fileprovider", fileInfo); // 授予WebView读取权限 webView.Context.GrantUriPermission(webView.Context.PackageName, uri, Android.Content.ActivityFlags.GrantReadUriPermission); audioUri = uri.ToString(); #endif // 构造HTML并加载到WebView string html = $@" <audio controls> <source src=""{audioUri}"" type=""audio/mpeg""> Your browser does not support the audio element. </audio>"; webView.Source = new HtmlWebViewSource { Html = html };
三、更推荐的方案:使用MAUI原生MediaElement控件
如果不需要WebView的复杂交互,直接用MAUI原生MediaElement控件更稳定:
1. 在XAML中添加控件
<MediaElement x:Name="LocalMediaPlayer" AutoPlay="False" />
2. 在代码中设置播放源
string fullPath = Path.Combine(FileSystem.AppDataDirectory, "Download", "2012-05-06_AM1.mp3"); LocalMediaPlayer.Source = new FileMediaSource { FilePath = fullPath }; // 开始播放 LocalMediaPlayer.Play();
内容的提问来源于stack exchange,提问作者Tony Hughes
相关产品推荐
相关产品推荐

