c#UWP扫描音乐文件

时间:2016-05-31 13:15:34

标签: c# windows-store-apps uwp universal

我正在为Windows 10实现一个音乐播放器,而且我在图书馆阶段有点蠢事。

我正在扫描音乐库中的所有文件(以及用户选择的可选文件夹),我还需要获取他们的标签(只需要标题和艺术家,不需要复杂的细节)。

问题在于表现。如果您有大型媒体库,获取音乐属性需要花费很多。目前我正在做以下事情:

private void UserControl_Loaded(object sender, RoutedEventArgs e)
    {
        Task.Factory.StartNew(async () =>
        {
            try
            {
                var files = await StorageHelper.GetFiles(KnownFolders.MusicLibrary);
                List<LocalAudio> tempList = new List<LocalAudio>();
                foreach (var file in files)
                {
                    MusicProperties properties = await file.Properties.GetMusicPropertiesAsync();

                    var title = string.IsNullOrWhiteSpace(properties.Title) ? file.Name : properties.Title;
                    var artist = string.IsNullOrWhiteSpace(properties.Artist) ? file.Path : properties.Artist;
                    tempList.Add(new LocalAudio() { Title = title, FilePath = file.Path, Artist = artist, Duration = properties.Duration });
                    if (tempList.Count > 50)
                    {
                        await AddToLibrary(tempList);
                        tempList.Clear();
                    }
                }
                await AddToLibrary(tempList);
                tempList.Clear();
            }
            catch (Exception ex)
            {
                //log exception here
            }
        });
    }

    private async Task AddToLibrary(List<LocalAudio> tempList)
    {
        await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
        {
            foreach (var item in tempList)
            {
                this.LocalFiles.Add(item);
            }
        });
    }

“LocalAudio”是我的音频模型,this.LocalFiles是一个ObservableCollection。 此外,StorageHelper.GetFiles(StorageFolder)方法返回一个IEnumerable的StorageFiles(音乐文件)(这是一个深入的递归方法)。

我在调度程序线程上添加了50个批量的文件,所以我不会阻止UI(我知道,即使它是一个异步方法在我开始的任务中运行而且忘记它仍会阻止UI,如果我连续添加它们......)。

我的问题是:我怎样才能更好地优化它? 任何想法都是好的。我想扫描它们一次并将音乐属性(标题,艺术家和持续时间)保存在一个文件中并在应用程序启动时读取该文件,然后将文件名与我在该文件中的数据同步(字典或其他内容并阅读文件并将其保存在内存中)。不确定这个想法有多好。

感谢您花时间阅读我的愚蠢问题:)

0 个答案:

没有答案