【问题标题】:How to list all .mp3 files in my android device in Xamarin如何在 Xamarin 中列出我的 android 设备中的所有 .mp3 文件
【发布时间】:2020-08-23 19:18:45
【问题描述】:
我正在尝试在 Xamarin.Forms 中开发音乐播放器应用程序。我想在我的 android 设备的 Music 文件夹中播放歌曲。如何获取所有 .mp3 文件?
这是我的歌曲模型。
namespace MusicPlayer.Models
{
public class Song
{
public string Title { get; set; }
public string Artist { get; set; }
public string Url { get; set; }
public string AlbumImageUri { get; set; }
public object Image { get; set; }
public string ImageUri { get; set; }
public bool IsRecent { get; set; }
public TimeSpan Duration { get; set; }
public string Genre { get; set; }
public string ReleaseYear { get; set; }
}
}
【问题讨论】:
标签:
c#
android
.net
xamarin
xamarin.forms
【解决方案1】:
首先你需要为你的项目添加权限。
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
在后面的代码中
List<Dictionary<string, string>> GetPlayList(string rootPath)
{
List<Dictionary<string, string>> fileList = new List<Dictionary<string, string>>();
try
{
File rootFolder = new File(rootPath);
File[] files = rootFolder.ListFiles(); //here you will get NPE if directory doesn't contains any file,handle it like this.
foreach (var file in files)
{
if (file.IsDirectory)
{
if (GetPlayList(file.AbsolutePath) != null)
{
fileList = new List<Dictionary<string, string>>(GetPlayList(file.AbsolutePath));
}
else
{
break;
}
}
else if (file.Name.EndsWith(".mp3"))
{
Dictionary<string, string> song = new Dictionary<string, string>();
song.Add("file_path", file.AbsolutePath);
song.Add("file_name", file.Name);
fileList.Add(song);
}
}
return fileList;
}
catch (Exception e)
{
return null;
}
}
你可以像调用它一样调用它
List<Dictionary<string, string>> songList = GetPlayList("/storage/sdcard1/");