How to set srcObject on audio element with React

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

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.