Shamoon
Shamoon

Reputation: 43569

How can I do a simple AJAX call to play audio via React / Redux?

I am trying to auto play some audio, and on iOS, it won't autoplay. However, if I wrap it in an AJAX call, it'll fire. So here's what I have:

// run on page load
var audio = document.getElementById('audio');

jQuery.ajax({
    url: 'ajax.js',
    async: false,
    success: function() {
        audio.play(); // audio will play in iOS before 4.2.1
    }
});

How would I set this up with React / Redux?

Upvotes: 0

Views: 513

Answers (1)

Fabian Schultz
Fabian Schultz

Reputation: 18556

Here's a very simple example using fetch (which is supported by most browsers out of the box) and blob object URLs. You could of course also use jQuery's ajax.

It's very similar to your code, but inside the componentDidMount method. The audio element is referenced via React's refs.

class Player extends React.Component {
  componentDidMount() {
    fetch(this.props.src)
      .then(res => res.blob())
      .then(blob => {
        const { audio } = this.refs;
        audio.src = URL.createObjectURL(blob);
        audio.play();
      });
  }
  render() {
    return <audio ref="audio" controls></audio>;
  }
}

ReactDOM.render(
  <Player src="https://ia802508.us.archive.org/5/items/testmp3testfile/mpthreetest.mp3" />,
  document.getElementById("View")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id='View'></div>
šŸ”Šā—ļø

Also, it is usually not recommended to use refs in React, but since we need access to the actual DOM node of the audio player it is a necessary evil.

Upvotes: 2

Related Questions