Skip to content
Advertisement

Custom Audio Player in react JS – Volume Control

I am building an custom audio player in React JS, I am current stuck with the volume controls in the audio player

Here is my code

Progress bar works fine, What should be logic behind the volume control

const [currentTime, setCurrentTime] = useState(0);
const progressBar = useRef();
const audioPlayer = useRef();

AduioPlayer.js

....
<audio
    ref={audioPlayer}
    src="something.mp3"
    preload="auto"
    volume
  ></audio>
// Volume Control Range slider
<input
    type="range"
    defaultValue="0"
    className="mx-2 progressBarvolume bar volume"
/>

// Progress Bar 
<input
    type="range"
    className="progressBar bar"
    defaultValue="0"
    ref={progressBar}
    onChange={changeRange}
/>
....

changeRange function :

const changeRange = () => {
    audioPlayer.current.currentTime = progressBar.current.value;
    changePlayerCurrentTime();
};

changePlayerCurrentTime function :

const changePlayerCurrentTime = () => {
    progressBar.current.style.setProperty(
        "--seek-before-width",
        `${(progressBar.current.value / duration) * 100}%`
    );
    setCurrentTime(progressBar.current.value);
};

Advertisement

Answer

Audio HTML Elements have a volume property you can access. You will need to have an onChange event in your audio slider.

Something like this within your onChange method will work:

audioPlayer.current.volume = e.target.value / 100;

where e is the ChangeEvent passed into the onChange method.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement