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
JavaScript
x
4
1
const [currentTime, setCurrentTime] = useState(0);
2
const progressBar = useRef();
3
const audioPlayer = useRef();
4
AduioPlayer.js
JavaScript
1
24
24
1
.
2
<audio
3
ref={audioPlayer}
4
src="something.mp3"
5
preload="auto"
6
volume
7
></audio>
8
// Volume Control Range slider
9
<input
10
type="range"
11
defaultValue="0"
12
className="mx-2 progressBarvolume bar volume"
13
/>
14
15
// Progress Bar
16
<input
17
type="range"
18
className="progressBar bar"
19
defaultValue="0"
20
ref={progressBar}
21
onChange={changeRange}
22
/>
23
.
24
changeRange function :
JavaScript
1
5
1
const changeRange = () => {
2
audioPlayer.current.currentTime = progressBar.current.value;
3
changePlayerCurrentTime();
4
};
5
changePlayerCurrentTime function :
JavaScript
1
8
1
const changePlayerCurrentTime = () => {
2
progressBar.current.style.setProperty(
3
"--seek-before-width",
4
`${(progressBar.current.value / duration) * 100}%`
5
);
6
setCurrentTime(progressBar.current.value);
7
};
8
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.