mediahub-fe/components/audio-player.tsx

62 lines
1.6 KiB
TypeScript
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import React, { useRef, useState, useEffect } from "react";
interface AudioPlayerProps {
urlAudio: string;
fileName: string; // ✅ Tambahkan props ini
}
const AudioPlayer: React.FC<AudioPlayerProps> = ({ urlAudio, fileName }) => {
const audioRef = useRef<HTMLAudioElement>(null);
const [currentTime, setCurrentTime] = useState(0);
const playAudio = () => {
audioRef.current?.play();
};
const pauseAudio = () => {
audioRef.current?.pause();
};
const stopAudio = () => {
if (audioRef.current) {
audioRef.current.pause();
audioRef.current.currentTime = 0;
}
};
useEffect(() => {
const audio = audioRef.current;
if (!audio) return;
const updateTime = () => {
setCurrentTime(audio.currentTime);
};
audio.addEventListener("timeupdate", updateTime);
return () => {
audio.removeEventListener("timeupdate", updateTime);
};
}, []);
const formatTime = (time: number) => {
const minutes = Math.floor(time / 60);
const seconds = Math.floor(time % 60).toString().padStart(2, "0");
return `${minutes}:${seconds}`;
};
return (
<div className="mt-2">
<h2 className="text-lg font-semibold">{fileName}</h2>
<audio ref={audioRef} src={urlAudio} controls className="mt-1 w-full" />
<div className="mt-2 space-x-2">
<button onClick={playAudio}> Play</button>
<button onClick={pauseAudio}> Pause</button>
<button onClick={stopAudio}> Stop</button>
</div>
<div className="mt-1 text-sm text-gray-500">{formatTime(currentTime)}</div>
</div>
);
};
export default AudioPlayer;