63 lines
1.5 KiB
TypeScript
63 lines
1.5 KiB
TypeScript
|
|
import React, { useRef, useState, useEffect } from "react";
|
|||
|
|
|
|||
|
|
const AudioPlayer = (props: {urlAudio: string}) => {
|
|||
|
|
const audioRef = useRef<HTMLAudioElement>(null);
|
|||
|
|
const [currentTime, setCurrentTime] = useState(0);
|
|||
|
|
const {urlAudio} = props
|
|||
|
|
|
|||
|
|
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 style={{ textAlign: "center", marginTop: "50px" }}>
|
|||
|
|
<h2>Pemutar Audio</h2>
|
|||
|
|
<audio ref={audioRef} src={urlAudio} />
|
|||
|
|
<div style={{ marginTop: "10px" }}>
|
|||
|
|
<button onClick={playAudio}>▶️ Play</button>
|
|||
|
|
<button onClick={pauseAudio}>⏸️ Pause</button>
|
|||
|
|
<button onClick={stopAudio}>⏹️ Stop</button>
|
|||
|
|
</div>
|
|||
|
|
<div style={{ marginTop: "10px" }}>
|
|||
|
|
<span>{formatTime(currentTime)}</span>
|
|||
|
|
</div>
|
|||
|
|
</div>
|
|||
|
|
);
|
|||
|
|
};
|
|||
|
|
|
|||
|
|
export default AudioPlayer;
|