rhythmbullet/RhythmBullet/Audio/MusicList.cs

116 lines
3.1 KiB
C#
Raw Normal View History

using System;
using System.Collections.Generic;
2018-11-20 05:05:59 +00:00
using System.Diagnostics;
using System.IO;
using System.Threading;
2018-12-04 05:05:54 +00:00
namespace RecrownedAthenaeum.Audio
{
2018-11-20 05:05:59 +00:00
internal delegate void SearchListener(MusicList musicList);
internal class MusicList
{
2018-11-20 05:05:59 +00:00
public event SearchListener SearchCompleteEvent;
private volatile bool work;
private List<string> list = new List<string>();
public List<string> List
{
get
{
if (!thread.IsAlive)
{
lock (list)
{
return list;
}
}
else
{
return null;
}
}
}
2018-11-20 05:05:59 +00:00
public string path;
private Thread thread;
2018-11-20 05:05:59 +00:00
public bool Searched
{
get
{
return (thread != null && !thread.IsAlive);
}
}
2018-11-20 05:05:59 +00:00
internal MusicList()
{
}
2018-11-20 05:05:59 +00:00
public void StartSearch()
{
if (thread == null || !thread.IsAlive)
{
work = true;
thread = new Thread(Search);
2018-11-20 05:05:59 +00:00
thread.IsBackground = true;
thread.Name = "Music Search Thread";
2018-11-20 05:05:59 +00:00
Debug.WriteLine("Starting music file search with path: " + path, GetType().Name);
thread.Start();
}
2018-11-20 05:05:59 +00:00
else
{
StopSearch();
StartSearch();
}
}
2018-11-20 05:05:59 +00:00
public void StopSearch()
{
work = false;
2018-11-20 05:05:59 +00:00
thread.Join();
}
private void Search()
{
lock (list)
{
2018-11-20 05:05:59 +00:00
list.Clear();
list.AddRange(recursiveMusicSearch(path));
}
2018-11-20 05:05:59 +00:00
OnSearchComplete();
Debug.WriteLine("Completed search. Found " + list.Count + " valid file(s).", GetType().Name);
}
private List<string> recursiveMusicSearch(string path)
{
List<string> musicFiles = new List<string>();
2018-11-20 05:05:59 +00:00
string[] folders = Directory.GetDirectories(path);
string[] files = Directory.GetFiles(path);
2018-11-20 05:05:59 +00:00
for (int folderID = 0; folderID < folders.Length && work; folderID++)
{
2018-11-20 05:05:59 +00:00
musicFiles.AddRange(recursiveMusicSearch(folders[folderID]));
}
for (int fileID = 0; fileID < files.Length && work; fileID++)
{
string extensionType = Path.GetExtension(files[fileID]).ToUpper().Substring(1);
SupportedFormats format;
2018-12-09 23:21:15 +00:00
if (Enum.TryParse<SupportedFormats>(extensionType, out format))
{
2018-11-20 05:05:59 +00:00
musicFiles.Add(files[fileID]);
}
else
{
2018-11-20 05:05:59 +00:00
Debug.WriteLine("Unsupported file format: " + Path.GetFileName(files[fileID]), GetType().Name);
}
}
return musicFiles;
}
2018-11-20 05:05:59 +00:00
private void OnSearchComplete()
{
SearchCompleteEvent?.Invoke(this);
}
}
}