audio 获取时长方法 (react)

方法一:创建audio标签,播放之后获取duration

let audioE = document.createElement("audio"); // 获取时长
audioE.src = configUrl.photoUrl + res.key;
audioE.load();
audioE.oncanplay = function () {
    setTimeout(()=> {
        console.log(audioE.duration);                    
        _this.setState({                      
            viewAudio: configUrl.photoUrl + res.key,
            duration: audioE.duration,
            audioLoading: false,
        });
    }, 1500);
}

方法二:使用react的一个插件 'react-audio-player';

1,安装并引入

import ReactAudioPlayer from 'react-audio-player';

2,使用组件

{/*判断是否已有音频 url*/} { this.state.site.enAudio ? ( { this.state.duration.enDuration = element }} ref={(element) => { this.setState({duration: element})}} // ref={(element) => { this.state.duration = element }} src={this.state.site.enAudio} onCanPlay={this.onCanPlay} /> ) : null }

3,获取音频地址

site: {
    ..._this.state.site,
    enAudio: global.config.photoUrl + res.key,
    enAudio_copy: res.key,
},

4,播放音频:

onCanPlay = () => {      
    let duration = this.state.duration;        
    let enDuration = duration ? Math.round(duration.audioEl.duration) : null;
    this.setState({
        site: {
            ...this.state.site,
            enDuration: enDuration
        }
    })
};

5,// 音频时长为 this.state.site.enDuration 

你可能感兴趣的:(js,react,video)