This creates sliders that control the volume of each individual audio:
import React, { useState, useEffect, useRef } from 'react';
function NoiseSlider({ noiseSrc }) {
const [volume, setVolume] = useState(0.5);
const audioRef = useRef(new Audio(noiseSrc));
useEffect(() => {
const audio = audioRef.current;
audio.volume = volume;
audio.loop = true;
audio.play();
return () => audio.pause();
}, [volume]);
return (
<input
type="range"
min="0"
max="1"
step="0.01"
value={volume}
onChange={(e) => setVolume(parseFloat(e.target.value))}
/>
);
}
export function App() {
return (
<div className="slider-container">
<NoiseSlider noiseSrc="https://onlinetestcase.com/wp-content/uploads/2023/06/100-KB-MP3.mp3" />
<NoiseSlider noiseSrc="https://onlinetestcase.com/wp-content/uploads/2023/06/500-KB-MP3.mp3" />
</div>
);
}
How to affect the volume
state of all NoiseSlider
s at once? For example, resetting all of them to 0.5 with a single button?
Live code at StackBlitz.
2
Answers
"NoiseSlider" is a custom element so it’s anyone’s guess how it was constructed.
But had it been the standard audio player then you could’ve just done this to set all volume levels at once…
I hope this helps.
You may want to give the above loop a try with…
But I wouldn’t hold my breath for this… 🙂
This can be achieved by the famous Lifting the state up principle. You can simply lift the state up to a common ancestor component, and pass down the volume state and a function to set the volume for all sliders as props.
CODE DEMO