Media Player
Play, pause, seek, and mute controls for an audio source.
Preview
Loading...
import { useEffect, useState } from "react";
import { MediaPlayer } from "@/components/ui/MediaPlayer";
export function MediaPlayerDemo() {
const [src, setSrc] = useState<string>();
useEffect(() => {
const sampleRate = 8000;
const samples = 800;
const buffer = new ArrayBuffer(44 + samples * 2);
const view = new DataView(buffer);
const write = (offset: number, text: string) => {
for (let index = 0; index < text.length; index += 1) {
view.setUint8(offset + index, text.charCodeAt(index));
}
};
write(0, "RIFF");
view.setUint32(4, 36 + samples * 2, true);
write(8, "WAVE");
write(12, "fmt ");
view.setUint32(16, 16, true);
view.setUint16(20, 1, true);
view.setUint16(22, 1, true);
view.setUint32(24, sampleRate, true);
view.setUint32(28, sampleRate * 2, true);
view.setUint16(32, 2, true);
view.setUint16(34, 16, true);
write(36, "data");
view.setUint32(40, samples * 2, true);
for (let index = 0; index < samples; index += 1) {
const sample = Math.sin((2 * Math.PI * 440 * index) / sampleRate) * 0.2;
view.setInt16(44 + index * 2, Math.round(sample * 0x7fff), true);
}
const url = URL.createObjectURL(new Blob([buffer], { type: "audio/wav" }));
setSrc(url);
return () => URL.revokeObjectURL(url);
}, []);
return <MediaPlayer src={src} />;
}Installation
Make sure that namespace is set in your component.json file. Namespace docs: Learn more about namespaces
pnpm dlx shadcn@latest add @aura/media-playerManual
Copy and paste the button component into your components/ui/Button.tsx file.
/**
* @description Displays a button or a component that looks like a button.
*/
import * as React from "react";
import { Slot } from "@radix-ui/react-slot";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/utils/class-names";
import { Spinner } from "@/components/ui/Spinner";
const buttonVariants = cva("button", {
variants: {
variant: {
default: "button-fill",
fill: "button-fill",
pill: "button-pill border border-gray-6 text-gray-11 bg-gray-2 hover:bg-gray-3",
link: "button-link",
menu: "button-menu",
},
size: {
default: "h-4",
xs: "h-2.5",
sm: "h-3",
md: "h-4",
lg: "h-5",
xl: "h-6",
icon: "w-3 h-3 p-0",
"icon-md": "w-4 h-4 p-0",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
});
interface ButtonProps
extends React.ComponentProps<"button">,
VariantProps<typeof buttonVariants> {
asChild?: boolean;
isDisabled?: boolean;
isLoading?: boolean;
isLoadingText?: string | React.ReactNode;
mode?: VariantProps<typeof buttonVariants>["variant"];
label?: string | React.ReactNode;
}
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
(props: ButtonProps, ref) => {
const {
className,
variant,
mode,
size,
asChild = false,
isDisabled,
isLoading,
isLoadingText,
children,
label,
...rest
} = props;
const Comp = asChild ? Slot : "button";
const disabled = isDisabled || isLoading || props.disabled;
const effectiveVariant = variant ?? mode;
return (
<Comp
data-slot="button"
className={cn(
buttonVariants({ variant: effectiveVariant, size, className }),
disabled && "opacity-50 cursor-not-allowed"
)}
ref={ref}
disabled={disabled}
{...rest}
>
{asChild ? (
children
) : (
<>
{isLoading && isLoadingText ? (
isLoadingText
) : (
<>
{isLoading ? <Spinner /> : null}
{label}
{children}
</>
)}
</>
)}
</Comp>
);
}
);
Button.displayName = "Button";
export { Button, buttonVariants };
export type { ButtonProps };
export default Button;
Copy and paste the class names utility into your utils/class-names.ts file.
import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
Copy and paste the MediaPlayer component into your components/ui/MediaPlayer.tsx file.
"use client";
import * as React from "react";
import { cn } from "@/utils/class-names";
import { Button } from "@/components/ui/Button";
function formatTime(seconds: number) {
if (!Number.isFinite(seconds) || seconds < 0) return "0:00";
const whole = Math.floor(seconds);
const minutes = Math.floor(whole / 60);
const remain = whole % 60;
return `${minutes}:${remain.toString().padStart(2, "0")}`;
}
function MediaPlayer({
className,
src,
label = "Media player",
}: {
className?: string;
src?: string;
label?: string;
}) {
const media = React.useRef<HTMLAudioElement>(null);
const [playing, setPlaying] = React.useState(false);
const [muted, setMuted] = React.useState(false);
const [time, setTime] = React.useState(0);
const [duration, setDuration] = React.useState(0);
const toggle = () => {
const node = media.current;
if (!node) return;
if (node.paused) void node.play();
else node.pause();
};
return (
<div
role="group"
aria-label={label}
data-slot="media-player"
className={cn("flex w-full max-w-xl flex-col gap-0.5 rounded-sm border border-gray-6 bg-gray-1 p-1", className)}
>
<audio
ref={media}
src={src}
preload="metadata"
onPlay={() => setPlaying(true)}
onPause={() => setPlaying(false)}
onTimeUpdate={(event) => setTime(event.currentTarget.currentTime)}
onDurationChange={(event) => setDuration(event.currentTarget.duration)}
onVolumeChange={(event) => setMuted(event.currentTarget.muted)}
/>
<div className="flex items-center gap-0.5">
<Button type="button" size="sm" aria-label={playing ? "Pause" : "Play"} onClick={toggle}>
{playing ? "Pause" : "Play"}
</Button>
<Button
type="button"
variant="pill"
size="sm"
aria-pressed={muted}
aria-label={muted ? "Unmute" : "Mute"}
onClick={() => {
if (media.current) media.current.muted = !media.current.muted;
}}
>
{muted ? "Unmute" : "Mute"}
</Button>
<span className="text-gray-11">
{formatTime(time)} / {formatTime(duration)}
</span>
</div>
<input
type="range"
min={0}
max={duration || 0}
step={0.1}
value={Math.min(time, duration || 0)}
aria-label="Seek"
onChange={(event) => {
const next = Number(event.target.value);
if (media.current) media.current.currentTime = next;
setTime(next);
}}
/>
</div>
);
}
export { MediaPlayer };