Add Option to shuffle playQueue

This commit is contained in:
Neshura 2024-05-02 03:53:11 +02:00
parent e2f8adc5db
commit 19d35589be
Signed by: Neshura
GPG key ID: B6983AAA6B9A7A6C
5 changed files with 25 additions and 4 deletions

View file

@ -62,7 +62,8 @@
<Button onclick={() => playbackState.pause()}>Pause</Button>
{/if}
<Button class="border p-2" onclick={() => playbackState.song.currentTime += 5}>{">>"}</Button>
<Button class="border p-2" onclick={() => playbackState.mode.next()}>{playbackState.mode.get()}</Button>
<Button class="border p-2" onclick={() => playbackState.loopMode.next()}>{playbackState.loopMode.get()}</Button>
<Button class="botder p-2" onclick={() => playbackState.shuffle = !playbackState.shuffle}>{playbackState.shuffle ? "X" : "="}</Button>
</div>
{:else}
<p>Nothing going on here</p>

View file

@ -16,6 +16,7 @@ interface QueueState {
firstSong: () => Song,
findSong: (song: Song) => {found: boolean, index: number},
addSong: (song: Song) => void,
replaceQueue: (newQueue: Array<Song>) => void,
getPlayQueue: (addNowPlaying: boolean) => Promise<void>,
saveQueue: () => Promise<void>,
}
@ -55,6 +56,11 @@ export const queueState: QueueState = $state({
this.queue.push(newSong);
this.currentIndex = this.queue.length - 1;
},
replaceQueue(newQueue: Array<Song>): void {
console.log(newQueue)
this.queue = [...newQueue];
this.currentIndex = 0;
},
async getPlayQueue(addNowPlaying: boolean = false): Promise<void> {
const queueData: GetPlayQueueResponse = await OpenSubsonic.get("getPlayQueue")
if (queueData && queueData.playQueue.entry) {

View file

@ -2,8 +2,17 @@ import {PlaybackMode, PlaybackStateSvelte} from "$lib/player.svelte";
import {OpenSubsonic, type Parameter, type Song} from "$lib/opensubsonic";
import {queueState} from "$lib/states/play-queue.svelte";
export const shuffle = (array: Array<Song>) => {
for (let i: number = array.length - 1; i > 0; i--) {
const j: number = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
return array;
};
interface PlaybackState {
mode: PlaybackStateSvelte,
loopMode: PlaybackStateSvelte,
shuffle: boolean,
song: HTMLAudioElement,
metaData: Song,
duration: number,
@ -16,7 +25,8 @@ interface PlaybackState {
}
export const playbackState: PlaybackState = $state({
mode: new PlaybackStateSvelte(),
loopMode: new PlaybackStateSvelte(),
shuffle: false,
song: {},
metaData: {},
duration: 0,
@ -63,7 +73,7 @@ export const playbackState: PlaybackState = $state({
}
this.song.onended = () => {
switch (this.mode.current) {
switch (this.loopMode.current) {
case PlaybackMode.Linear: {
this.newSong(queueState.nextSong());
this.play();
@ -75,6 +85,10 @@ export const playbackState: PlaybackState = $state({
}
case PlaybackMode.LoopQueue: {
if (queueState.currentIndex === queueState.queue.length -1) {
if (this.shuffle) {
const shuffledQueue = shuffle([...queueState.queue])
queueState.replaceQueue(shuffledQueue);
}
this.newSong(queueState.firstSong());
}
else {

View file

View file