Skip to content
0.2.0-dev Download ZIP
119 lines ·2.8 KB Raw
1namespace EvilEngine.Music.Playback;
2
3public enum RepeatMode
4{
5 Off,
6 All,
7 One
8}
9
10public sealed class PlayQueue(Random? random = null)
11{
12 public const double RestartAfterSeconds = 3;
13
14 private readonly Random random = random ?? Random.Shared;
15 private List<string> items = [];
16 private List<int> order = [];
17 private int position = -1;
18 private bool shuffle;
19
20 public IReadOnlyList<string> Items => items;
21 public RepeatMode Repeat { get; set; }
22 public string? Current => position >= 0 && position < order.Count ? items[order[position]] : null;
23 public IEnumerable<string> Upcoming => order.Skip(position + 1).Select(index => items[index]);
24
25 public bool Shuffle
26 {
27 get => shuffle;
28 set
29 {
30 if (shuffle == value)
31 return;
32 shuffle = value;
33 var current = position >= 0 && position < order.Count ? order[position] : -1;
34 Order(current);
35 }
36 }
37
38 public string? Play(IReadOnlyList<string> list, int start)
39 {
40 items = [.. list];
41 if (items.Count == 0)
42 {
43 order = [];
44 position = -1;
45 return null;
46 }
47
48 Order(Math.Clamp(start, 0, items.Count - 1));
49 return Current;
50 }
51
52 public string? Next(bool ended)
53 {
54 if (order.Count == 0)
55 return null;
56 if (ended && Repeat == RepeatMode.One)
57 return Current;
58 if (position + 1 < order.Count)
59 {
60 position++;
61 return Current;
62 }
63
64 if (Repeat == RepeatMode.Off)
65 {
66 if (ended)
67 position = order.Count;
68 return null;
69 }
70
71 if (shuffle)
72 Order(-1);
73 position = 0;
74 return Current;
75 }
76
77 public string? Previous(double seconds)
78 {
79 if (order.Count == 0)
80 return null;
81 if (seconds > RestartAfterSeconds || (position <= 0 && Repeat != RepeatMode.All))
82 {
83 position = Math.Clamp(position, 0, order.Count - 1);
84 return Current;
85 }
86
87 position = position <= 0 ? order.Count - 1 : position - 1;
88 return Current;
89 }
90
91 public void Clear()
92 {
93 items = [];
94 order = [];
95 position = -1;
96 }
97
98 private void Order(int current)
99 {
100 order = Enumerable.Range(0, items.Count).ToList();
101 if (!shuffle)
102 {
103 position = current;
104 return;
105 }
106
107 if (current >= 0)
108 order.Remove(current);
109 for (var i = order.Count - 1; i > 0; i--)
110 {
111 var j = random.Next(i + 1);
112 (order[i], order[j]) = (order[j], order[i]);
113 }
114
115 if (current >= 0)
116 order.Insert(0, current);
117 position = current >= 0 ? 0 : -1;
118 }
119}