如何在Xamarin.Forms中多选音视频文件并配置MediaPlugin创建播放列表
Hey there! Let's get your playlist feature up and running. You're on the right track with exploring plugins—since Xamarin.Forms doesn't have a built-in multi-file picker, third-party plugins are the way to go. Let's break down how to use MediaPlugin first, plus cover Android configuration and alternative options if needed.
Step 1: Finalize Android Configuration for MediaPlugin
First, let's make sure your Android project is set up correctly, since that's where you're focusing right now:
Update AndroidManifest.xml:
- Add these permissions inside the
<manifest>tag (adjust based on Android version):<!-- For Android < 13 --> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="28" /> <!-- For Android 13+ --> <uses-permission android:name="android.permission.READ_MEDIA_AUDIO" /> <uses-permission android:name="android.permission.READ_MEDIA_VIDEO" /> - Add
android:requestLegacyExternalStorage="true"to your<application>tag (this helps with file access on Android 10+):<application android:requestLegacyExternalStorage="true" ...>
- Add these permissions inside the
Handle Runtime Permissions:
On Android 6.0+, you need to request storage permissions at runtime. You can use Xamarin.Essentials to do this easily:var status = await Permissions.CheckStatusAsync<Permissions.StorageRead>(); if (status != PermissionStatus.Granted) { status = await Permissions.RequestAsync<Permissions.StorageRead>(); } // For Android 13+, use Permissions.MediaAudio or Permissions.MediaVideo instead
Step 2: Use MediaPlugin to Select Multiple Files
MediaPlugin does support multi-file selection—you just need to set the right option in PickMediaOptions:
Here's a code snippet you can use in your Xamarin.Forms page or ViewModel:
using Plugin.Media; using Plugin.Media.Abstractions; // Command to trigger file selection public ICommand SelectMediaFilesCommand => new Command(async () => { // Check if media plugin is available if (!CrossMedia.Current.IsPickMediaSupported) { await Application.Current.MainPage.DisplayAlert("Oops", "Media picking isn't supported on this device.", "OK"); return; } // Configure picker for multiple audio/video files var options = new PickMediaOptions { SelectionMode = MediaSelectionMode.Multiple, // Filter to only show audio/video files (optional but recommended) MediaType = MediaType.AllMedia // Or use MediaType.Audio / MediaType.Video }; var selectedFiles = await CrossMedia.Current.PickMediaAsync(options); if (selectedFiles != null && selectedFiles.Any()) { // Store these file paths for your playlist foreach (var file in selectedFiles) { var filePath = file.Path; // Add filePath to your playlist collection (e.g., ObservableCollection<string>) PlaylistItems.Add(filePath); } // Save the playlist to local storage (e.g., SQLite, JSON file) await SavePlaylistAsync(PlaylistItems); } });
Step 3: Save Your Playlist
Once you have the selected file paths, you'll want to persist the playlist. A simple way is to save it as a JSON file using Xamarin.Essentials:
using System.Text.Json; using Xamarin.Essentials; private async Task SavePlaylistAsync(List<string> playlistPaths) { var json = JsonSerializer.Serialize(playlistPaths); await FileSystem.WriteAllTextAsync(FileSystem.AppDataDirectory + "/playlist.json", json); } // To load the playlist later private async Task<List<string>> LoadPlaylistAsync() { var filePath = FileSystem.AppDataDirectory + "/playlist.json"; if (File.Exists(filePath)) { var json = await FileSystem.ReadAllTextAsync(filePath); return JsonSerializer.Deserialize<List<string>>(json); } return new List<string>(); }
Alternative: Use FilePicker Plugin for More Control
If MediaPlugin doesn't fit your needs (e.g., you want more file type filtering), the FilePicker Plugin is a great alternative. It's specifically built for file selection and supports multi-file picks:
- Install the NuGet package for the plugin.
- Android configuration is similar (same permissions as above).
- Code example for selection:
using Plugin.FilePicker; using Plugin.FilePicker.Abstractions; public async Task<List<string>> PickMultipleMediaFiles() { var filePaths = new List<string>(); try { var files = await CrossFilePicker.Current.PickMultipleFilesAsync(); if (files != null) { foreach (var file in files) { // Check if it's an audio/video file (optional) if (file.ContentType.StartsWith("audio/") || file.ContentType.StartsWith("video/")) { filePaths.Add(file.FilePath); } } } } catch (Exception ex) { await Application.Current.MainPage.DisplayAlert("Error", $"Failed to pick files: {ex.Message}", "OK"); } return filePaths; }
Key Notes
- Always test on physical devices—emulators can have file access quirks.
- For Android 13+, make sure to request the new
READ_MEDIA_AUDIO/READ_MEDIA_VIDEOpermissions instead ofREAD_EXTERNAL_STORAGE. - When saving playlists, use app-specific storage (via
FileSystem.AppDataDirectory) to avoid issues with file access restrictions.
内容的提问来源于stack exchange,提问作者Dharm Rajodiya

