在后台管理項目中,用戶要求上傳音頻,並且自動獲取音頻時長。
第一步, import { Upload, Button, Icon } from 'antd';
第二步,在表單中使用 Upload 組件,上傳音頻:
<FormItem {...formItemLayout} label="英文音頻信息">
<Row gutter={8}>
<Col span={12}>
<Input type="text" placeholder="景點的英文音頻信息" value={site.enAudio} disabled />
</Col>
<Col span={12}>
<Upload
action="/hserve/v2/file/upload/" // 必選參數,上傳的地址
listType="picture" // 上傳列表的內建樣式(text、picture、picture-card)
showUploadList={false} // 是否顯示 uploadList
accept="audio/*" // 接受上傳的文件類型
fileList={enAudioFileList} // 已經上傳的文件列表
onChange={this.handleAudioChange} // 上傳文件改變時的狀態
>
<Button>
<Icon type="upload" /> 瀏覽
</Button>
</Upload>
</Col>
</Row>
</FormItem>
handleAudioChange = (type, { file, fileList }) => {
if (file.status === 'done') {
fileList[fileList.length - 1].url = file.response.path
let lastFile = fileList[fileList.length - 1]
this.setState({
enAudioFileList: fileList,
site: { ...this.state.site, enAudio: lastFile.url }
})
return
}
this.setState({ enAudioFileList: fileList })
}
第三步,使用 react-audio-player:
import ReactAudioPlayer from 'react-audio-player'
{
site.cnAudio //判斷是否已有音頻 url
? (
<ReactAudioPlayer
ref={(element) => { duration.cnDuration = element; }}
src={site.cnAudio}
onCanPlay={this.onCanPlay}
/>
)
: null
}
onCanPlay = () => {
let duration = this.state.duration
// duration.enDuration.audioEl.duration 返回的是一個帶小數的數字,因此用 Math.round 做了下處
let enDuration = duration.enDuration ? Math.round(duration.enDuration.audioEl.duration) : null
enDuration = enDuration ? this.setDuration(enDuration) : null
this.setState({
site: {...this.state.site, enDuration: enDuration}
})
}
// 將 duration 設為 00:00 的格式
setDuration = (sec) => {
let min = 0
sec = sec <=10 ? '0' + sec : sec
if (sec >= 60) {
min = (sec / 60).toFixed()
sec = sec % 60 >= 10 ? sec % 60 : '0' + sec % 60
}
min = min >= 10 ? min : '0' + min
let time = min + ':' + sec
return time
}
音頻時長為 this.state.site.enDuration。