Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React - refs - audio playback - Unhandled Rejection (NotSupportedError) on iOS

Tags:

reactjs

media

I built a react app that plays/pauses the currently selected audio just fine on desktop web browser:

playPreview() {
    if (!this.state.isPlaying) {
      this.setState({ isPlaying: true });
      this.refs.audioRef.play();
    } else {
      this.setState({ isPlaying: false });
      this.refs.audioRef.pause();
    }
  }

On iOS mobile browsers (safari and chrome mobile) I get an unhandled rejection (NotSupprted Error): The operation is not supported.

I'm aware of the issue that on iOS the audio must play from a user's gesture but I'm firing off my method with an onClick:

{!props.isPlaying 
  ? (<MdPlayCircleOutline className="play-btn" onClick={() => 
    props.playPreview()} />) 
  : (<MdPauseCircleOutline className="play-btn" onClick={() => 
    props.playPreview()} />)
}

I have an hidden element in the parent app component:

<audio ref="audioRef" src={this.state.currentSongUrl} style={{ display: 'none' }} />

So I'm assuming that it doesn't work because the onClick isn't directly audio element? If that's the case I'm sure how to combine these two requirements.

1 - Dynamically changing audio source 2 - Alternate playback and pause

Thanks in advance to any insight and help!

-Todd

like image 962
Todd Matthews Avatar asked Feb 12 '18 13:02

Todd Matthews


1 Answers

This might be happening because you are using deprecated syntax for ref. You should try something like this:

<audio ref={(input) => {this.audioRef = input}} src={this.state.currentSongUrl} style={{ display: 'none' }} />

and

playPreview() {
  if (!this.state.isPlaying) {
    this.setState({ isPlaying: true });
    this.audioRef.play();
  } else {
    this.setState({ isPlaying: false });
    this.audioRef.pause();
  }
}

For reference, visit: Refs and the DOM

like image 112
Arslan Tariq Avatar answered Sep 24 '22 13:09

Arslan Tariq