How to set srcObject on audio element with React

。_饼干妹妹 提交于 2020-07-08 04:56:30

问题


I've been trying to set the src attribute of an audio tag in React, but the track never plays.

playTrack(track) {
    const stream = new MediaStream()
    stream.addTrack(track)
    this.setState(() => ({ stream }))
}

render() {
    return (
        <audio src={this.state.stream || null} controls volume="true" autoPlay />
    )
}

When I check in the chrome debugger it shows that the audio tag has [MediaStream] set as its source, but nothing plays and all the controls remained grayed out.

Doing this instead of setting the state works, but I presume this is highly frowned upon in React.

const audio = document.querySelector('audio')
audio.srcObject = stream

回答1:


If storing the stream in the state is not a requirement, then you can update the srcObject property using a ref:

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 />
    )
}

If you do need to access the stream from the state you can try this

<audio ref={audio => { audio.srcObject = this.state.stream }} />

The reason src={this.state.stream} doesn't work is because src expects a string that represents the url of the audio resource while this.state.stream is a MediaStream object.

audio.src and audio.srcObject are different properties that expect different value types.




回答2:


For those who use props and don't like to create function on each render:

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
  }
}


来源:https://stackoverflow.com/questions/48603402/how-to-set-srcobject-on-audio-element-with-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!