feat: revamp the entire audio player with a refreshed look and cleanup audioPlayer code
This commit is contained in:
16 files changed
+1587
-771
No files matched your search
@@ -1,37 +1,39 @@
|
||||
import React, { useEffect, useMemo, useRef, useState } from "react";
|
||||
|
||||
import { motion } from "motion/react";
|
||||
|
||||
import Fab from "@mui/material/Fab";
|
||||
import IconButton from "@mui/material/IconButton";
|
||||
import Slider from "@mui/material/Slider";
|
||||
import Typography from "@mui/material/Typography";
|
||||
|
||||
import { setAudioRef, useAudioPlayback } from "@/utils/store/audioPlayback";
|
||||
import useQueue from "@/utils/store/queue";
|
||||
|
||||
import { AnimatePresence } from "motion/react";
|
||||
import "./audioPlayer.scss";
|
||||
|
||||
import { getRuntimeMusic, secToTicks, ticksToSec } from "@/utils/date/time";
|
||||
|
||||
import PlayNextButton from "@/components/buttons/playNextButton";
|
||||
import PlayPreviousButton from "@/components/buttons/playPreviousButtom";
|
||||
import QueueButton from "@/components/buttons/queueButton";
|
||||
import { useLocation, useNavigate } from "@tanstack/react-router";
|
||||
import { AnimatePresence, motion } from "motion/react";
|
||||
import React, { type SyntheticEvent, useEffect, useRef, useState } from "react";
|
||||
import { secToTicks, ticksToSec } from "@/utils/date/time";
|
||||
import getImageUrlsApi from "@/utils/methods/getImageUrlsApi";
|
||||
import { useApiInContext } from "@/utils/store/api";
|
||||
import {
|
||||
setAudioRef,
|
||||
setIsMuted,
|
||||
setVolume,
|
||||
useAudioPlayback,
|
||||
} from "@/utils/store/audioPlayback";
|
||||
import { useCentralStore } from "@/utils/store/central";
|
||||
import { playItemFromQueue } from "@/utils/store/playback";
|
||||
import { useNavigate } from "@tanstack/react-router";
|
||||
import useQueue from "@/utils/store/queue";
|
||||
import PlayerActions from "./components/PlayerActions";
|
||||
import PlayerControls from "./components/PlayerControls";
|
||||
import PlayerInfo from "./components/PlayerInfo";
|
||||
import PlayerProgress from "./components/PlayerProgress";
|
||||
import PlayerVolume from "./components/PlayerVolume";
|
||||
|
||||
import "./audioPlayer.scss";
|
||||
|
||||
const AudioPlayer = () => {
|
||||
const api = useApiInContext((s) => s.api);
|
||||
const user = useCentralStore((s) => s.currentUser);
|
||||
const navigate = useNavigate();
|
||||
const location = useLocation();
|
||||
|
||||
const audioRef = useRef<HTMLAudioElement | null>(null);
|
||||
const [url, display, item] = useAudioPlayback((state) => [
|
||||
const [url, display, item, volume, isMuted] = useAudioPlayback((state) => [
|
||||
state.url,
|
||||
state.display,
|
||||
state.item,
|
||||
state.player.volume,
|
||||
state.player.isMuted,
|
||||
]);
|
||||
|
||||
const [tracks, currentTrack] = useQueue((state) => [
|
||||
@@ -39,327 +41,213 @@ const AudioPlayer = () => {
|
||||
state.currentItemIndex,
|
||||
]);
|
||||
|
||||
const user = useCentralStore((s) => s.currentUser);
|
||||
|
||||
const playing = useMemo(() => {
|
||||
if (audioRef.current?.paused) return false;
|
||||
return true;
|
||||
}, [audioRef.current?.paused]);
|
||||
const [volume, setVolume] = useState(0.8);
|
||||
const [isMuted, setIsMuted] = useState(false);
|
||||
const [playing, setPlaying] = useState(false);
|
||||
const [progress, setProgress] = useState(0);
|
||||
const [isScrubbing, setIsScrubbing] = useState(false);
|
||||
const [sliderProgress, setSliderProgress] = useState(0);
|
||||
|
||||
// Sync volume and ref
|
||||
useEffect(() => {
|
||||
if (display) {
|
||||
// const audioUrlRequest = new Request(audioRef.current?.dataset.src, {
|
||||
// method: "GET",
|
||||
// headers: {
|
||||
// Authorization: api.authorizationHeader,
|
||||
// },
|
||||
// });
|
||||
// fetch(audioUrlRequest)
|
||||
// .then((res) => res)
|
||||
// .then(async (result) => {
|
||||
// const blob = await result.blob();
|
||||
// const blobUrl = URL.createObjectURL(blob);
|
||||
// audioRef.current.src = blobUrl;
|
||||
// await audioRef.current.play();
|
||||
// setLoading(false);
|
||||
// });
|
||||
|
||||
// Set the audio ref in the store to allow for global control
|
||||
setAudioRef(audioRef);
|
||||
if (audioRef.current) {
|
||||
audioRef.current.volume = isMuted ? 0 : volume;
|
||||
}
|
||||
}
|
||||
}, [url, tracks?.[currentTrack]?.Id]);
|
||||
}, [display, url, tracks?.[currentTrack]?.Id]);
|
||||
|
||||
const navigate = useNavigate();
|
||||
// Update volume when state changes
|
||||
useEffect(() => {
|
||||
if (audioRef.current) {
|
||||
audioRef.current.volume = isMuted ? 0 : volume;
|
||||
}
|
||||
}, [volume, isMuted]);
|
||||
|
||||
const info = useMemo(
|
||||
() =>
|
||||
api && (
|
||||
<div
|
||||
// initial={{
|
||||
// filter: "opacity(0)",
|
||||
// }}
|
||||
// animate={{
|
||||
// filter: "opacity(1)",
|
||||
// }}
|
||||
// exit={{
|
||||
// filter: "opacity(0)",
|
||||
// }}
|
||||
className="audio-player-info"
|
||||
>
|
||||
<div className="audio-player-image-container">
|
||||
<img
|
||||
alt={tracks?.[currentTrack]?.Name ?? "track"}
|
||||
className="audio-player-image"
|
||||
src={getImageUrlsApi(api).getItemImageUrlById(
|
||||
(!item?.ImageTags?.Primary ? item?.AlbumId : item.Id) ?? "",
|
||||
"Primary",
|
||||
{
|
||||
quality: 85,
|
||||
fillHeight: 462,
|
||||
fillWidth: 462,
|
||||
},
|
||||
)}
|
||||
/>
|
||||
<span className="material-symbols-rounded audio-player-image-icon">
|
||||
music_note
|
||||
</span>
|
||||
</div>
|
||||
<div className="audio-player-info-text">
|
||||
<Typography
|
||||
variant="subtitle2"
|
||||
style={{
|
||||
width: "100%",
|
||||
}}
|
||||
>
|
||||
{item?.Name}
|
||||
</Typography>
|
||||
<Typography
|
||||
variant="caption"
|
||||
style={{
|
||||
opacity: 0.5,
|
||||
}}
|
||||
noWrap
|
||||
>
|
||||
by {item?.Artists?.map((artist) => artist).join(",")}
|
||||
</Typography>
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
[tracks?.[currentTrack]?.Id, currentTrack, api?.configuration],
|
||||
);
|
||||
// Media Session Metadata
|
||||
useEffect(() => {
|
||||
if ("mediaSession" in navigator && item) {
|
||||
const imageUrl = item.ImageTags?.Primary
|
||||
? api &&
|
||||
getImageUrlsApi(api).getItemImageUrlById(item.Id ?? "", "Primary", {
|
||||
tag: item.ImageTags.Primary,
|
||||
})
|
||||
: undefined;
|
||||
|
||||
const controls = useMemo(
|
||||
() => (
|
||||
<div style={{ display: "flex", gap: "1em" }}>
|
||||
<PlayPreviousButton />
|
||||
<div
|
||||
style={{
|
||||
display: "inline-flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
position: "relative",
|
||||
}}
|
||||
>
|
||||
<Fab
|
||||
size="small"
|
||||
onClick={() =>
|
||||
audioRef.current?.paused
|
||||
? audioRef.current.play()
|
||||
: audioRef.current?.pause()
|
||||
}
|
||||
>
|
||||
<div
|
||||
className="material-symbols-rounded"
|
||||
style={{
|
||||
fontSize: "2em",
|
||||
}}
|
||||
>
|
||||
{playing ? "pause" : "play_arrow"}
|
||||
</div>
|
||||
</Fab>
|
||||
</div>
|
||||
<PlayNextButton />
|
||||
</div>
|
||||
),
|
||||
[tracks?.[currentTrack]?.Id, playing, tracks?.length],
|
||||
);
|
||||
|
||||
const buttons = useMemo(
|
||||
() => (
|
||||
<div
|
||||
style={{
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "flex-end",
|
||||
}}
|
||||
>
|
||||
<IconButton onClick={() => navigate({ to: "/player/audio" })}>
|
||||
<span className="material-symbols-rounded">info</span>
|
||||
</IconButton>
|
||||
<QueueButton />
|
||||
<IconButton
|
||||
onClick={() => {
|
||||
setIsMuted(!isMuted);
|
||||
}}
|
||||
>
|
||||
<div className="material-symbols-rounded">
|
||||
{isMuted ? "volume_mute" : "volume_up"}
|
||||
</div>
|
||||
</IconButton>
|
||||
<Slider
|
||||
value={isMuted ? 0 : volume * 100}
|
||||
step={1}
|
||||
max={100}
|
||||
onChange={(_, newVal) => {
|
||||
if (!audioRef.current) {
|
||||
console.error("Audio ref not found");
|
||||
return;
|
||||
}
|
||||
Array.isArray(newVal)
|
||||
? setVolume(newVal[0] / 100)
|
||||
: setVolume(newVal / 100);
|
||||
if (Array.isArray(newVal)) {
|
||||
audioRef.current.volume = newVal[0] / 100;
|
||||
} else {
|
||||
audioRef.current.volume = newVal / 100;
|
||||
}
|
||||
}}
|
||||
valueLabelDisplay="auto"
|
||||
valueLabelFormat={(value) => Math.floor(value)}
|
||||
size="small"
|
||||
sx={{
|
||||
mr: 1,
|
||||
ml: 1,
|
||||
width: "10em",
|
||||
"& .MuiSlider-valueLabel": {
|
||||
lineHeight: 1.2,
|
||||
fontSize: 24,
|
||||
background: "rgb(0 0 0 / 0.5)",
|
||||
backdropFilter: "blur(5px)",
|
||||
padding: 1,
|
||||
borderRadius: "10px",
|
||||
border: "1px solid rgb(255 255 255 / 0.15)",
|
||||
boxShadow: "0 0 10px rgb(0 0 0 / 0.4) ",
|
||||
transform: "translatey(-120%) scale(0)",
|
||||
"&:before": {
|
||||
display: "none",
|
||||
navigator.mediaSession.metadata = new MediaMetadata({
|
||||
title: item.Name ?? "Unknown Title",
|
||||
artist: item.Artists?.join(", ") ?? "Unknown Artist",
|
||||
album: item.Album ?? "Unknown Album",
|
||||
artwork: imageUrl
|
||||
? [
|
||||
{
|
||||
src: imageUrl,
|
||||
sizes: "512x512",
|
||||
type: "image/jpeg",
|
||||
},
|
||||
"&.MuiSlider-valueLabelOpen": {
|
||||
transform: "translateY(-120%) scale(1)",
|
||||
},
|
||||
"& > *": {
|
||||
transform: "rotate(0deg)",
|
||||
},
|
||||
},
|
||||
}}
|
||||
/>
|
||||
<IconButton
|
||||
onClick={() => {
|
||||
useAudioPlayback.setState(useAudioPlayback.getInitialState());
|
||||
}}
|
||||
>
|
||||
<div className="material-symbols-rounded">close</div>
|
||||
</IconButton>
|
||||
</div>
|
||||
),
|
||||
[volume, isMuted, currentTrack],
|
||||
);
|
||||
]
|
||||
: [],
|
||||
});
|
||||
}
|
||||
}, [item, api]);
|
||||
|
||||
// if (audioRef.current) {
|
||||
// audioRef.current.addEventListener("change", () => {
|
||||
// console.log("Audio Player changed state : ", currentTrack);
|
||||
// });
|
||||
// audioRef.current.addEventListener("ended", () => {
|
||||
// Media Session Action Handlers
|
||||
useEffect(() => {
|
||||
if ("mediaSession" in navigator) {
|
||||
navigator.mediaSession.setActionHandler("play", () => {
|
||||
audioRef.current?.play();
|
||||
});
|
||||
navigator.mediaSession.setActionHandler("pause", () => {
|
||||
audioRef.current?.pause();
|
||||
});
|
||||
navigator.mediaSession.setActionHandler("previoustrack", () => {
|
||||
if (user?.Id && api) {
|
||||
playItemFromQueue("previous", user.Id, api);
|
||||
}
|
||||
});
|
||||
navigator.mediaSession.setActionHandler("nexttrack", () => {
|
||||
if (user?.Id && api) {
|
||||
playItemFromQueue("next", user.Id, api);
|
||||
}
|
||||
});
|
||||
navigator.mediaSession.setActionHandler("seekto", (details) => {
|
||||
if (audioRef.current && details.seekTime !== undefined) {
|
||||
audioRef.current.currentTime = details.seekTime;
|
||||
}
|
||||
});
|
||||
}
|
||||
}, [api, user?.Id]);
|
||||
|
||||
// });
|
||||
// }
|
||||
const updatePositionState = () => {
|
||||
if (
|
||||
"mediaSession" in navigator &&
|
||||
audioRef.current &&
|
||||
!Number.isNaN(audioRef.current.duration)
|
||||
) {
|
||||
try {
|
||||
navigator.mediaSession.setPositionState({
|
||||
duration: audioRef.current.duration,
|
||||
playbackRate: audioRef.current.playbackRate,
|
||||
position: audioRef.current.currentTime,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Error updating media session position state:", error);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handlePlayPause = () => {
|
||||
if (audioRef.current) {
|
||||
if (audioRef.current.paused) {
|
||||
audioRef.current.play();
|
||||
setPlaying(true);
|
||||
} else {
|
||||
audioRef.current.pause();
|
||||
setPlaying(false);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handleTimeUpdate = (e: SyntheticEvent<HTMLAudioElement>) => {
|
||||
setProgress(secToTicks(e.currentTarget.currentTime));
|
||||
};
|
||||
|
||||
const handleEnded = () => {
|
||||
setPlaying(false);
|
||||
if (tracks?.[currentTrack + 1]?.Id && api && user?.Id) {
|
||||
playItemFromQueue("next", user.Id, api);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSeekCommit = (value: number) => {
|
||||
if (audioRef.current) {
|
||||
audioRef.current.currentTime = ticksToSec(value);
|
||||
setProgress(value);
|
||||
}
|
||||
};
|
||||
|
||||
const handleVolumeChange = (newVolume: number) => {
|
||||
setVolume(newVolume);
|
||||
};
|
||||
|
||||
const handleMuteToggle = () => {
|
||||
setIsMuted(!isMuted);
|
||||
};
|
||||
|
||||
const handleClose = () => {
|
||||
useAudioPlayback.setState(useAudioPlayback.getInitialState());
|
||||
};
|
||||
|
||||
const handleNavigate = () => {
|
||||
navigate({ to: "/player/audio" });
|
||||
};
|
||||
|
||||
// Listen to play/pause events directly from audio element to keep state in sync
|
||||
// (e.g. if paused by media keys)
|
||||
const onPlay = () => {
|
||||
setPlaying(true);
|
||||
updatePositionState();
|
||||
if ("mediaSession" in navigator) {
|
||||
navigator.mediaSession.playbackState = "playing";
|
||||
}
|
||||
};
|
||||
const onPause = () => {
|
||||
setPlaying(false);
|
||||
updatePositionState();
|
||||
if ("mediaSession" in navigator) {
|
||||
navigator.mediaSession.playbackState = "paused";
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<AnimatePresence mode="sync">
|
||||
{display && (
|
||||
<motion.div
|
||||
initial={{
|
||||
transform: "translateY(100%)",
|
||||
}}
|
||||
initial={{ transform: "translate(-50%, 150%)" }}
|
||||
animate={{
|
||||
transform:
|
||||
location.pathname === "/player/audio"
|
||||
? "translateY(100%)"
|
||||
: "translateY(0%)",
|
||||
}}
|
||||
exit={{
|
||||
transform: "translateY(100%)",
|
||||
}}
|
||||
style={{
|
||||
width: "100%",
|
||||
}}
|
||||
transition={{
|
||||
duration: 0.2,
|
||||
ease: "easeInOut",
|
||||
? "translate(-50%, 150%)"
|
||||
: "translate(-50%, 0%)",
|
||||
}}
|
||||
exit={{ transform: "translate(-50%, 150%)" }}
|
||||
transition={{ duration: 0.3, ease: "circOut" }}
|
||||
className="audio-player glass"
|
||||
>
|
||||
{info}
|
||||
<PlayerInfo
|
||||
item={item}
|
||||
api={api}
|
||||
trackName={tracks?.[currentTrack]?.Name}
|
||||
/>
|
||||
|
||||
<audio
|
||||
autoPlay
|
||||
src={url}
|
||||
ref={audioRef}
|
||||
key={item?.Id ?? "noItem"}
|
||||
onTimeUpdate={(e) =>
|
||||
setProgress(secToTicks(e.currentTarget.currentTime))
|
||||
}
|
||||
onEnded={() => {
|
||||
if (tracks?.[currentTrack + 1]?.Id && api && user?.Id) {
|
||||
playItemFromQueue("next", user.Id, api);
|
||||
}
|
||||
}}
|
||||
onTimeUpdate={handleTimeUpdate}
|
||||
onEnded={handleEnded}
|
||||
onPlay={onPlay}
|
||||
onPause={onPause}
|
||||
onSeeked={updatePositionState}
|
||||
onLoadedMetadata={updatePositionState}
|
||||
id="audio-player"
|
||||
/>
|
||||
|
||||
<div className="audio-player-controls">
|
||||
{controls}
|
||||
<div
|
||||
style={{
|
||||
width: "100%",
|
||||
display: "flex",
|
||||
gap: "1em",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
}}
|
||||
>
|
||||
<Typography
|
||||
variant="subtitle2"
|
||||
fontWeight={300}
|
||||
style={{
|
||||
opacity: 0.8,
|
||||
}}
|
||||
>
|
||||
{getRuntimeMusic(progress)}
|
||||
</Typography>
|
||||
<Slider
|
||||
value={isScrubbing ? sliderProgress : progress}
|
||||
step={1}
|
||||
size="small"
|
||||
max={item?.RunTimeTicks ?? 1}
|
||||
onChange={(_, value) => {
|
||||
setIsScrubbing(true);
|
||||
Array.isArray(value)
|
||||
? setSliderProgress(value[0])
|
||||
: setSliderProgress(value);
|
||||
}}
|
||||
onChangeCommitted={(_, value) => {
|
||||
if (!audioRef.current) {
|
||||
console.error("Audio ref not found");
|
||||
return;
|
||||
}
|
||||
setIsScrubbing(false);
|
||||
// console.log(ticksToSec(value * item.RunTimeTicks));
|
||||
Array.isArray(value)
|
||||
? setProgress(value[0])
|
||||
: setProgress(value);
|
||||
if (Array.isArray(value)) {
|
||||
audioRef.current.currentTime = ticksToSec(value[0]);
|
||||
} else {
|
||||
audioRef.current.currentTime = ticksToSec(value);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<Typography
|
||||
variant="subtitle2"
|
||||
fontWeight={300}
|
||||
style={{
|
||||
opacity: 0.8,
|
||||
}}
|
||||
>
|
||||
{getRuntimeMusic(item?.RunTimeTicks ?? 0)}
|
||||
</Typography>
|
||||
</div>
|
||||
<PlayerControls playing={playing} onPlayPause={handlePlayPause} />
|
||||
<PlayerProgress
|
||||
progress={progress}
|
||||
duration={item?.RunTimeTicks ?? 1}
|
||||
onSeekCommit={handleSeekCommit}
|
||||
/>
|
||||
</div>
|
||||
{buttons}
|
||||
|
||||
<PlayerActions onNavigate={handleNavigate} onClose={handleClose}>
|
||||
<PlayerVolume
|
||||
volume={volume}
|
||||
isMuted={isMuted}
|
||||
onVolumeChange={handleVolumeChange}
|
||||
onMuteToggle={handleMuteToggle}
|
||||
/>
|
||||
</PlayerActions>
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
|
||||
Reference in new issue
Block a user