rhythmbullet/RhythmBullet/Audio/MusicList.cs

122 lines
3.3 KiB
C#
Raw Normal View History

using Microsoft.Xna.Framework.Media;
using System;
using System.Collections.Generic;
2018-11-20 05:05:59 +00:00
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace RhythmBullet.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;
bool supported = Enum.TryParse<SupportedFormats>(extensionType, out format);
if (supported)
{
2018-11-20 05:05:59 +00:00
musicFiles.Add(files[fileID]);
Debug.WriteLine("Music file found: " + files[fileID], GetType().Name);
}
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);
}
}
}