import React from 'react'; import styles from './index.less'; import { Progress } from 'antd'; import { PlayCircleOutlined, PauseCircleOutlined } from '@ant-design/icons'; import moment from 'moment'; import { SingleAudioContext } from '../single-audio'; interface AudioPlayerProps { url?: string; } const AudioPlayer: React.FC = props => { const { url } = props; const [playing, setPlaying] = React.useState(false); const [duration, setDuration] = React.useState(0); const [current, setCurrent] = React.useState(0); const audioRef = React.useRef(); const idRef = React.useRef(`${Date.now()}-${Math.random()}`); //不晓得为毛current会超过duration const percent = duration !== 0 ? (Math.min(current, duration) * 100) / duration : 0; const { playingId, setPlayingId } = React.useContext(SingleAudioContext); React.useEffect(() => { function handleTimeUpdate() { if (audioRef?.current) { setCurrent(audioRef?.current.currentTime); setDuration(audioRef?.current.duration); if (audioRef?.current?.duration <= audioRef?.current.currentTime) { handleStop(); setCurrent(0); } } } // function getAudioTime(): Promise { // return new Promise((resolve, reject) => { // const audio = audioRef?.current; // if (audio) { // audio.addEventListener("loadedmetadata", function() { // const duration = audio.duration; // resolve(duration); // }); // } else { // reject(); // } // }); // } async function init() { audioRef.current = new Audio(url); // const duration = await getAudioTime(); // setDuration(duration); audioRef.current.addEventListener('timeupdate', handleTimeUpdate); } if (url) { init(); } return () => { if (audioRef.current) { audioRef.current.removeEventListener('timeupdate', handleTimeUpdate); audioRef.current = undefined; } }; }, [url]); React.useEffect(() => { if (playingId !== idRef?.current) { handleStop(); } }, [playingId]); const handlePlay = () => { if (audioRef.current) { audioRef.current.play(); setPlaying(true); setPlayingId?.(idRef.current); } }; const handleStop = () => { if (audioRef.current) { audioRef.current.pause(); setPlaying(false); } }; return (
{playing ? ( ) : ( )} moment( moment() .startOf('day') .valueOf() + Math.min(current, duration) * 1000, ).format('HH:mm:ss') } strokeWidth={2} />
); }; export default AudioPlayer;