import React from "react";
import { Slider, Icon } from "antd";
import dayjs from "dayjs";
import durationPlugin from "dayjs/plugin/duration";
import utcPlugin from "dayjs/plugin/utc";
import "./index.less";
import iconLoading from "../../assert/loading.gif";
dayjs.extend(durationPlugin);
dayjs.extend(utcPlugin);
class AudioPlayer extends React.Component {
constructor(props) {
super(props);
this.state = {
duration: 0,
currentDuration: 0,
isPlaying: false,
isLoading: false
};
}
componentDidMount() {
if (this.player) {
const { src } = this.props;
this.player.oncanplay = event =>
this.setState({
duration: event.target.duration,
isLoading: false,
isPlaying: true
});
this.player.onended = () =>
this.setState({
isPlaying: false,
currentDuration: 0,
isLoading: false
});
this.player.onpause = () =>
this.setState({ isPlaying: false, isLoading: false });
this.player.onplay = () => this.setState({ isLoading: true });
this.player.ontimeupdate = event =>
this.setState({ currentDuration: event.target.currentTime });
this.player.src = src;
}
}
componentDidUpdate(prevProps) {
if (this.props.src !== prevProps.src) {
this.player.oncanplay = event =>
this.setState({
duration: event.target.duration,
isLoading: false,
isPlaying: true
});
this.player.onended = () =>
this.setState({
isPlaying: false,
currentDuration: 0,
isLoading: false
});
this.player.onpause = () =>
this.setState({ isPlaying: false, isLoading: false });
this.player.onplay = () => this.setState({ isLoading: true });
this.player.ontimeupdate = event =>
this.setState({ currentDuration: event.target.currentTime });
this.player.src = this.props.src;
}
}
clickPlayOrPause(isPlaying) {
if (!this.player) {
return;
}
if (isPlaying) {
this.player.pause();
} else {
// 如果是播放,先暂停其他的播放
const playerList = document.getElementsByTagName("audio");
if (playerList) {
Array.from(playerList).forEach(player => {
if (!player.paused) {
player.pause();
}
});
}
this.player.play();
}
}
getPlayIcon() {
const { isPlaying, isLoading } = this.state;
let playIconElem;
if (isLoading) {
playIconElem = ;
} else if (isPlaying) {
playIconElem =