Anoop K George
Anoop K George

Reputation: 1765

How to play/pause react-audio-player using state/external button

I have an audio player in react project. How can I start playing the player using an external button?

Repo: https://github.com/lhz516/react-h5-audio-player

I may need to reference the player using useRef or something

function Audio() {

  const audiofunction = () => {

    document.getElementById('player').play();

  };
  return (
    <div className="App">

      <AudioPlayer
        preload='metadata'
        src={song}
        onPlay={e => console.log("onPlay")}
        id='player'
      />

      <button onClick={audiofunction}>play</button>
    </div>
  );
}

BELOW CONTENT FROM DOCUMENT

Access to the audio element You can get direct access to the underlying audio element. First, get a ref to ReactAudioPlayer:

this.player = createRef()

  < ReactAudioPlayer ref = { this.player } />

Then you can access the audio element like this:

this.player.current.audio.current

Upvotes: 3

Views: 4448

Answers (1)

Anoop K George
Anoop K George

Reputation: 1765



import React,{useEffect,useState,useRef} from 'react';

import axios from 'axios';
import AudioPlayer from 'react-h5-audio-player';
import 'react-h5-audio-player/lib/styles.css';


function Audio() {
  const [song,setSong] = useState('');
  const player = useRef();
  useEffect(()=>{
    axios.get('http://localhost:8000/songs/').then(res=>setSong(res.data[0].track))
  },[]);
  const audiofunction = () => {


    player.current.audio.current.play();

  };
  return (
    <div className="App">


      <AudioPlayer 
   preload='metadata'
    src={song}
    onPlay={e => console.log("onPlay")}
    ref={player}
  />

   <button onClick={audiofunction}>play</button>
    </div>
  );
}

export default Audio

Upvotes: 5

Related Questions