当前位置: 代码迷 >> 综合 >> audio 获取时长方法 (react)
  详细解决方案

audio 获取时长方法 (react)

热度:31   发布时间:2023-11-21 15:58:06.0

方法一:创建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,使用组件

<div>{/*判断是否已有音频 url*/}{ this.state.site.enAudio ? (<ReactAudioPlayer // ref={(element) => { 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}
</div>

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 

  相关解决方案