Save autoplay state
This commit is contained in:
@@ -3,15 +3,20 @@
|
||||
import Image from "next/image";
|
||||
import ReactAudioPlayer from "react-audio-player";
|
||||
import {useEffect, useState} from "react";
|
||||
import { getCookie, setCookie } from "cookies-next";
|
||||
|
||||
export default function RecordBox() {
|
||||
let player: ReactAudioPlayer | null = null;
|
||||
let notes: HTMLImageElement | null = null;
|
||||
|
||||
const [firstSong, setFirstSong] = useState<string | undefined>();
|
||||
const [shouldAutoPlay, setShouldAutoPlay] = useState<boolean>(true);
|
||||
|
||||
useEffect(() => {
|
||||
setFirstSong(randomSong());
|
||||
// Get autoplay preference from cookie
|
||||
const autoplayCookie = getCookie('jukebox-autoplay');
|
||||
setShouldAutoPlay(autoplayCookie === 'true' || autoplayCookie === undefined);
|
||||
}, []);
|
||||
|
||||
return <div>
|
||||
@@ -29,21 +34,27 @@ export default function RecordBox() {
|
||||
if (player.audioEl.current.paused) {
|
||||
player.audioEl.current.play().then();
|
||||
notes.className = "bottom-23 right-0 fixed z-50 pb-2 pr-2";
|
||||
// Save preference for autoplay ON
|
||||
setCookie('jukebox-autoplay', 'true');
|
||||
setShouldAutoPlay(true);
|
||||
} else {
|
||||
player.audioEl.current.pause();
|
||||
notes.className = "hidden bottom-23 right-0 fixed z-50 pb-2 pr-2";
|
||||
// Save preference for autoplay OFF
|
||||
setCookie('jukebox-autoplay', 'false');
|
||||
setShouldAutoPlay(false);
|
||||
}
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</button>
|
||||
<ReactAudioPlayer
|
||||
autoPlay={true} controls={false} className=""
|
||||
autoPlay={shouldAutoPlay} controls={false} className=""
|
||||
volume={0.2}
|
||||
ref={(element) => { player = element; }}
|
||||
src={firstSong}
|
||||
onPlay={() => {started(player, notes)}}
|
||||
onEnded={() => {ended(player, notes)}}
|
||||
onEnded={() => {ended(player, notes, shouldAutoPlay)}}
|
||||
onPause={() => {stopped(player, notes)}}
|
||||
/>
|
||||
</div>
|
||||
@@ -61,11 +72,13 @@ function stopped(player: ReactAudioPlayer | null, notes: HTMLImageElement | null
|
||||
}
|
||||
}
|
||||
|
||||
function ended(player: ReactAudioPlayer | null, notes: HTMLImageElement | null) {
|
||||
function ended(player: ReactAudioPlayer | null, notes: HTMLImageElement | null, autoPlay: boolean = true) {
|
||||
if (player != null && notes != null) {
|
||||
notes.className = "hidden bottom-23 right-0 fixed z-50 pb-2 pr-2";
|
||||
player.audioEl.current.src = randomSong();
|
||||
player.audioEl.current.play().then();
|
||||
if (autoPlay) {
|
||||
player.audioEl.current.play().then();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user