74 lines
2.4 KiB
C#
74 lines
2.4 KiB
C#
using System.Collections.Generic;
|
||
using System.IO;
|
||
using UnityEngine;
|
||
|
||
// 已匯入的曲包清單:persistentDataPath/songs/<id>/
|
||
// 遊戲本身不內建任何曲目,所有歌曲都由曲包匯入
|
||
public static class SongLibrary
|
||
{
|
||
public const string CurrentPrefKey = "NowPlayingSong";
|
||
// Android 端(RhyculatorActivity.java)讀取失敗時寫在收件匣的訊息檔
|
||
public const string ImportErrorFile = "import-error.txt";
|
||
|
||
// 測試用:改放到別的資料夾
|
||
public static string rootOverride;
|
||
|
||
public static string RootDir => rootOverride ?? Path.Combine(Application.persistentDataPath, "songs");
|
||
|
||
// 放在這個資料夾的 *.zip 會在開啟遊戲 / 回到前景時自動匯入
|
||
public static string InboxDir => rootOverride != null ? Path.Combine(rootOverride, "inbox") : Application.persistentDataPath;
|
||
|
||
private static List<SongInfo> songs;
|
||
|
||
public static IReadOnlyList<SongInfo> Songs
|
||
{
|
||
get { if (songs == null) Reload(); return songs; }
|
||
}
|
||
|
||
public static void Reload()
|
||
{
|
||
var list = new List<SongInfo>();
|
||
if (Directory.Exists(RootDir))
|
||
{
|
||
foreach (var dir in Directory.GetDirectories(RootDir))
|
||
{
|
||
if (!File.Exists(Path.Combine(dir, SongInfo.ConfigName))) continue;
|
||
try
|
||
{
|
||
var s = SongInfo.FromDir(dir);
|
||
if (s.MusicPath != null && s.FirstLevel() > 0) list.Add(s);
|
||
else Debug.LogWarning($"[SongLibrary] 略過 {dir}:缺音樂或譜面");
|
||
}
|
||
catch (System.Exception e)
|
||
{
|
||
Debug.LogWarning($"[SongLibrary] 略過 {dir}:{e.Message}");
|
||
}
|
||
}
|
||
}
|
||
list.Sort((a, b) => string.Compare(a.name, b.name, System.StringComparison.OrdinalIgnoreCase));
|
||
songs = list;
|
||
}
|
||
|
||
public static SongInfo Find(string id)
|
||
{
|
||
foreach (var s in Songs) if (s.id == id) return s;
|
||
return null;
|
||
}
|
||
|
||
// 目前選擇的曲目;沒選過或已被刪除時取清單第一首
|
||
public static SongInfo Current
|
||
{
|
||
get
|
||
{
|
||
var s = Find(PlayerPrefs.GetString(CurrentPrefKey, ""));
|
||
return s ?? (Songs.Count > 0 ? Songs[0] : null);
|
||
}
|
||
set
|
||
{
|
||
if (value == null) return;
|
||
PlayerPrefs.SetString(CurrentPrefKey, value.id);
|
||
PlayerPrefs.Save();
|
||
}
|
||
}
|
||
}
|