javascript - 无法在 console.log 上获取音频的 currentTime
问题描述
我正在制作音乐播放器,我想获取音频的当前时间和持续时间。我在音频标签中使用了 ref 来选择它并使用它的属性。我需要音频的 currentTime 和持续时间,但出现错误。下面是代码
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 显示为空
如果我在返回部分注释掉两个“p”标签,然后在 componentWillMount 中使用 console.log,那么我得到(检查图像)当前为空,但在打开“当前”对象时,我得到“音频”
请帮助获取“当前时间”和“持续时间”,以便我可以使我的进度条工作在此先感谢
解决方案
您错过的是,初始渲染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>
);
}
让我知道这是否适合您。
推荐阅读
- python - 使用判别函数的多类分类
- c# - 如果我在数据网格中进行任何更改,然后想将该详细信息显示到另一个数据网格
- mongodb - 使用聚合检查数组中是否存在值
- cmake - 在 yocto 项目中创建符号链接失败
- c# - ASP.NET Boilerplate 允许自配置租户注册
- system-verilog-dpi - 在 systemverilog 和 DPI-C 之间使用定义
- qt - 当文本包含阿拉伯语单词时如何检查文本的自动对齐
- haskell - 为什么第三个 let-in 语句有错误?
- ios - 如何将多个数组字符串加入单个数组?
- node.js - Upsert 和 $inc 数组中的子文档