Reputation: 151
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);
};
Upvotes: 2
Views: 9495
Reputation: 89
If you are just planning to build a custom UI with Audio player it would be better to go with already existing library that makes working with Web Audio API easier.Usually, Howler is popular choice to go. You could have a look here with reactjs https://github.com/shohinrahmonov/react-tunes
Upvotes: 0
Reputation: 1
This how I worked on mine
import React from 'react';
import './Progress.css';
export default function Progress() {
React.useEffect(() => {
const knob = window.document.querySelector('.knob');
const progress = window.document.querySelector('.progress')
progress.addEventListener("mouseover", (event) =>knob.style.left = event.offsetX + "px")
}, []);
return (
<div className="progress" >
<div className="path comp"></div>
<div className="knob comp" ></div>
</div>
)
}
.progress{
top: 10px;
width: 100%;
height: 20px;
}
.progress .path{
background-color: #fff;
width: 100%;
height: 4px;
border-radius: 2px;
top: 50%;
transform: translateY(-50%);
}
.progress .knob{
background-color: crimson;
width: 7px;
height: 15px;
left: 20px;
border-radius: 2px;
top: 50%;
transform: translateY(-50%);
transition:all .2s linear ;
pointer-events: none;
transform: translate(-50%, -50%);
}
.progress .comp{
position: absolute;
}
Upvotes: 0
Reputation: 462
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.
Upvotes: 1