Reactjs 如何使用React在音频元素上设置srcObject
我一直在尝试在React中设置音频标记的Reactjs 如何使用React在音频元素上设置srcObject,reactjs,web-audio-api,Reactjs,Web Audio Api,我一直在尝试在React中设置音频标记的src属性,但曲目从未播放过 playTrack(track) { const stream = new MediaStream() stream.addTrack(track) this.setState(() => ({ stream })) } render() { return ( <audio src={this.state.stream || null} controls volum
src
属性,但曲目从未播放过
playTrack(track) {
const stream = new MediaStream()
stream.addTrack(track)
this.setState(() => ({ stream }))
}
render() {
return (
<audio src={this.state.stream || null} controls volume="true" autoPlay />
)
}
如果不需要将流存储在状态中,则可以使用
ref
更新srcObject
属性:
playTrack(track) {
const stream = new MediaStream()
stream.addTrack(track)
this.audio.srcObject = stream;
}
render() {
return (
<audio ref={audio => {this.audio = audio}} controls volume="true" autoPlay />
)
}
playTrack(曲目){
const stream=new MediaStream()
stream.addTrack(track)
this.audio.srcObject=流;
}
render(){
返回(
{this.audio=audio}}控制音量=“true”自动播放/>
)
}
如果您确实需要从状态访问流,您可以尝试以下操作
<audio ref={audio => { audio.srcObject = this.state.stream }} />
{audio.srcObject=this.state.stream}/>
src={this.state.stream}
不起作用的原因是src
需要一个表示音频资源url的字符串,而this.state.stream
是一个MediaStream
对象
audio.src
和audio.srcObject
是需要不同值类型的不同属性。对于使用道具且不希望在每个渲染上创建函数的用户:
constructor(props) {
super(props)
this.videoRef = React.createRef()
}
render() {
return <video ref={this.videoRef}/>
}
componentDidMount() {
this.updateVideoStream()
}
componentDidUpdate() {
this.updateVideoStream()
}
updateVideoStream() {
if (this.videoRef.current.srcObject !== this.props.stream) {
this.videoRef.current.srcObject = this.props.stream
}
}
构造函数(道具){
超级(道具)
this.videoRef=React.createRef()
}
render(){
返回
}
componentDidMount(){
this.updateVideoStream()
}
componentDidUpdate(){
this.updateVideoStream()
}
updateVideoStream(){
if(this.videoRef.current.srcObject!==this.props.stream){
this.videoRef.current.srcObject=this.props.stream
}
}
I get audio在使用您的示例时为null,在用作ref之前我是否应该在其他地方定义音频?@AJ_u可能在构造函数上,您需要this.audio=React.createRef()代码>?是的,就是这样。如果我有一个流的数组,并且使用该数组我必须创建audia标记怎么办?
constructor(props) {
super(props)
this.videoRef = React.createRef()
}
render() {
return <video ref={this.videoRef}/>
}
componentDidMount() {
this.updateVideoStream()
}
componentDidUpdate() {
this.updateVideoStream()
}
updateVideoStream() {
if (this.videoRef.current.srcObject !== this.props.stream) {
this.videoRef.current.srcObject = this.props.stream
}
}