在React项目中,React提供了自带的音频播放器组件,即react-audio-player,安装命令如下:
npm install --save react-audio-player
在安装之后,可以在React项目代码中,如下使用:
import ReactAudioPlayer from 'react-audio-player';
export type Props = {
current?: any;
};
const DemoPage: React.FC<Props> = (props) => {
const wordAudioRef = useRef(null)
;
const onPlay = ()=>{
const currentRef: any = wordAutoAudioRef.current;
if (currentRef == null) {
return;
}
const audioObj = currentRef.audioEl.current;
audioObj.src = '音频文件URL';
}
return (<>
<ReactAudioPlayer ref={wordAudioRef} autoPlay/>
<button onClick={()=>{onPlay();}} >Play</button>
</>);
}
上面示例代码是自动播放音频,也可以收工播放,代码如下:
wordAutoAudioRef.current.audioEl.current.play();
包括暂停(停止)播放和重新加载:
wordAutoAudioRef.current.audioEl.current.pause();
wordAutoAudioRef.current.audioEl.current.load();