gpt4 book ai didi

javascript - 无法在 console.log 上获取音频的当前时间

转载 作者:行者123 更新时间:2023-11-30 06:21:00 25 4
gpt4 key购买 nike

我正在制作一个音乐播放器,我想获取音频的当前时间和持续时间。我在音频标签中使用 ref 来选择它并使用它的属性。我需要音频的当前时间和持续时间,但出现错误。下面是代码

import React, { Component, createRef } from 'react';
import ProgressBar from '../progressBar/progressBar'

class Control extends Component {
state={
isPlaying: false,
songNow: this.props.source,
}
player= createRef();

componentWillMount(){
console.log('WILL UPDATE')
console.log(this.player)// first log {current: null} then after fraction of second {current:audio}
}

componentDidUpdate(){

console.log("COMPONENT DID UPDATE")
console.log(this.state.isPlaying)
console.log(this.player.current.duration)// it logs Nan
setTimeout(()=> console.log(this.player.current.duration), 200)// this shows the duration


if(this.state.isPlaying){

this.player.current.play();
console.log('if load play')
console.log(this.props.currentSong.songUrl)
console.log(this.state.songNow)


}
else if(!this.state.isPlaying){

this.player.current.pause()
console.log('pause')
}
}
componentWillReceiveProps=(nextProps)=>{
console.log("COMPONENT WILL RECEIVE PROPS")

if(this.props.currentSong.songUrl !== nextProps.currentSong.songUrl){
this.setState({
songNow: nextProps.currentSong.songUrl,
isPlaying: true
})
this.player.current.pause()
this.player.current.load()
this.player.current.play()
console.log('willrcvprop')
}
//some other functions

}
render(){

return (
<div className="controls">

<p>{this.player.current.currentTime}</p> {/*// Cannot read property 'currentTime' of null*/}
<ProgressBar width="200px" player={this.player} />
<p>{this.player.current.duration}</p> {/*// Cannot read property 'duration' of null*/}

<audio ref={this.player} onEnded={()=>this.onNext()} >
<source
src={this.props.currentSong.songUrl}
type="audio/mp3"/>
</audio>
//some other codes
)
}
}

this.player.current 显示为空

without removing the 'p'tag

如果我在 return 部分注释掉两个 'p' 标签,然后在 componentWillMount 中使用 console.log 然后我得到(检查图像)current is null but on opening the 'current' object I get the 'audio'

请帮助获取“当前时间”和“持续时间”,以便我可以使我的进度条正常工作 提前致谢

最佳答案

您错过的是,在初始渲染时 this.player 可能没有完全准备好使用,这就是错误的原因。我建议始终检查您使用的变量是否可用。

试试这个:

  render() {
return (
<div className="controls">
<p>
{this.player && this.player.current
? this.player.current.currentTime
: 0}
</p>
{/*// Cannot read property 'currentTime' of null*/}
<ProgressBar width="200px" player={this.player} />
<p>
{this.player && this.player.current
? this.player.current.duration
: 0}
</p>
{/*// Cannot read property 'duration' of null*/}
<audio ref={this.player} onEnded={() => this.onNext()}>
<source src={this.props.currentSong.songUrl} type="audio/mp3" />
</audio>
</div>
);
}

让我知道这是否适合您。

关于javascript - 无法在 console.log 上获取音频的当前时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53116298/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com