问题描述
import React,{ useEffect,useRef,useState } from "react";
import { usedispatch,useSelector } from 'react-redux'
import { format,formWaveSurferOptions } from '../../utils/generic'
import { receiveCurrentTrack,receiveTrackRef,togglePlay} from '../../redux/action/currentTrack'
import './_playlist.scss'
import WaveSurfer from "wavesurfer.js";
import {Link} from 'react-router-dom';
const PlayList = (props) => {
const dispatch = usedispatch()
const { track,queue,currentTrack,index } = props
const waveformRef = useRef(null);
const waveRef = useSelector((state)=>state.currentTrack.waveRef)
const wavesurfer = useRef(null);
const currentTime = useRef(null)
const [duration,setDuration] = useState()
useEffect(() => {
const options = formWaveSurferOptions(waveformRef.current);
wavesurfer.current = WaveSurfer.create(options);
wavesurfer.current.load(track.url);
wavesurfer.current.on("ready",()=> {
if(wavesurfer.current){
wavesurfer.current.setVolume(0)
setDuration(format(wavesurfer.current.getDuration()))
}
});
return () => wavesurfer.current.destroy();
},[track.url]);
useEffect(()=>{
if(currentTrack){
dispatch(receiveTrackRef(wavesurfer))
}
return ()=> waveRef?.current.stop()
},[currentTrack.track?.url])
const handleClick = () => {
dispatch(receiveTrackRef(wavesurfer))
if(currentTrack){
dispatch(togglePlay())
}
else {
waveRef?.current.stop()
dispatch(receiveCurrentTrack(track,queue));
}
};
return (
<div
className={ currentTrack ? "playlist-item selected playlist" : "playlist-item playlist"}
onClick={handleClick}
>
<div># {index} :</div>
<Link to='/track'>{track.title}</Link>
<div>{track.artist}</div>
<div><span>0.00</span> / {duration && duration}</div>
<div className="wave-form" id="waveform" onChange={()=>console.log('hhh')} ref={waveformRef} />
<div>{duration && duration}</div>
</div>
);
};
export default PlayList;
React-Wavesurfer 没有维护,所以我已经转移到了 wavesurfer.js,但问题出现了现在我如何检测音频当前时间并显示到页面,例如0:01 / 3.02,我使用了 wavesurfer.on('audioprocess') 但我无法检测到它,所以如果有人知道解决方案,请帮忙,谢谢:)
解决方法
来自Official Doc:
getCurrentTime() – 以秒为单位返回当前进度。
还有一个 audioprocess
事件,正如您提到的 fires continuously as the audio plays。
因此,通过将这些组合在一起,我们得到了:
let current;
wavesurfer.on('audioprocess',() => {
current = wavesurfer.getCurrentTime();
});
请注意,您的 wavesurfer 播放器被指定为名称 wavesurfer.current
。所以代码应该是 wavesurfer.current.on('audioprocess',() => {});