Search code examples
reactjshtml5-audio

Unable to pause audio in Reactjs


I've followed the other posts that have asked similar questions, but they have not provided a solution.

I'm not able to pause audio in my React Hook.

This is my react hook:

import React, { useState } from "react";

export default (App = props => {
  const [audioStatus, changeAudioStatus] = useState(false);
  const audio = new Audio(
    "https://mcdn.podbean.com/mf/web/xm5ngf/The_Challenge_Chronicles_-_Episode_48_7ys6e.mp3"
  );
  audio.load();

  const startAudio = () => {
    audio.play();

    changeAudioStatus(true);
  };

  const pauseAudio = () => {
    console.log("here");
    audio.pause();
    changeAudioStatus(false);
  };

  return (
    <>
      {audioStatus ? (
        <button onClick={pauseAudio}>pause</button>
      ) : (
        <button onClick={startAudio}>start</button>
      )}
    </>
  );

I've also created a sandbox: https://codesandbox.io/s/great-gagarin-v0vi1


Solution

  • You can use the audio tag, and pass a ref to react, so that it will know what element is being used.

    working example

    export default (App = props => {
      const [audioStatus, changeAudioStatus] = useState(false);
      const myRef = useRef();
    
      const startAudio = () => {
        myRef.current.play();
    
        changeAudioStatus(true);
      };
    
      const pauseAudio = () => {
        console.log("here");
        myRef.current.pause();
        changeAudioStatus(false);
      };
    
      return (
        <>
          <audio
            ref={myRef}
            src="https://mcdn.podbean.com/mf/web/xm5ngf/The_Challenge_Chronicles_-_Episode_48_7ys6e.mp3"
          />
          {audioStatus ? (
            <button onClick={pauseAudio}>pause</button>
          ) : (
            <button onClick={startAudio}>start</button>
          )}
        </>
      );
    });