React JS upload audio from local machine and play in browser

Viewed 890

I want to upload an audio file from my local machine and play it when the button click. I searched for it but I didn't find the solution that I wanted. I tried to use the Audio method of JS. I could able to play audio but I couldn't pause it. Please help me to solve this issue.

My code is

import React, { useEffect, useState } from 'react';
import {useForm} from "react-hook-form";

const AudioPlay = () => {
  const[buttonName,setButtonName] = useState('Play')
  const [audio,setAudio] = useState();

  var a;

  if(audio){
   a=new Audio(audio) 
  }

  const handleClick = () => {
    if (buttonName==='Play') {
      a.play()
      setButtonName('Pause')
    } else {
      a.pause()
      setButtonName('Play')
    }
   }

  const addFile = (e) => {
    const s=URL.createObjectURL(e.target.files[0])
    setAudio(s)
  }

  return (    
    <div>    
       <button onClick={handleClick}>{buttonName}</button>
       <input type='file' onChange={addFile} /> 
    </div >
  )
}

export default AudioPlay;
1 Answers

You need to manipulation your audio in the useEffect hooks to prevent replacing the audio object in each render.

import React, { useState, useEffect } from "react";

var a;
const AudioPlay = () => {
  const [buttonName, setButtonName] = useState("Play");

  const [audio, setAudio] = useState();

  useEffect(() => {
    if (a) {
      a.pause();
      a = null;
      setButtonName("Play");
    }
    if (audio) {
      a = new Audio(audio);
      a.onended = () => {
        setButtonName("Play");
      };
    }
  }, [audio]);

  const handleClick = () => {
    if (buttonName === "Play") {
      a.play();
      setButtonName("Pause");
    } else {
      a.pause();
      setButtonName("Play");
    }
  };

  const addFile = (e) => {
    if (e.target.files[0]) {
      setAudio(URL.createObjectURL(e.target.files[0]));
    }
  };

  return (
    <div>
      <button onClick={handleClick}>{buttonName}</button>
      <input type="file" onChange={addFile} />
    </div>
  );
};

export default AudioPlay;

Live Demo

Codesandbox Demo

Related