Based on an array, I’m trying to create audio elements and [Slider][1]s to control their volume:
import { useState, useRef, useEffect } from 'react';
import Slider from 'rc-slider';
import 'rc-slider/assets/index.css';
function App() {
const initialAudioSources = [
{ src: '/fire.mp3', volume: 1 },
{ src: '/ocean.mp3', volume: 1 },
// Add more audio sources as needed
];
const [audios, setAudios] = useState([]);
const audioRefs = useRef([]);
useEffect(() => {
// Create audio elements and set initial volume for each audio source
const audioElements = initialAudioSources.map((audioSource) => {
const audio = new Audio(audioSource.src);
audio.volume = audioSource.volume;
audio.loop = true;
return audio;
});
setAudios(audioElements);
audioRefs.current = audioElements.map(() => useRef(null));
// Start playing the audios
audioElements.forEach((audio, index) => {
if (audioRefs.current[index].current) {
audioRefs.current[index].current.volume = audio.volume;
audioRefs.current[index].current.play();
}
});
}, []);
const handleSliderChange = (newValue, index) => {
const updatedAudios = audios.map((audio, i) => {
if (i === index && audioRefs.current[i].current) {
audioRefs.current[i].current.volume = newValue / 100;
}
return audio;
});
setAudios(updatedAudios);
};
return (
<>
<div className="audio-controls">
{audios.map((audio, index) => (
<div key={index} className="audio-control">
<audio ref={audioRefs.current[index]} controls>
<source src={initialAudioSources[index].src} type="audio/mpeg" />
Your browser does not support the audio element.
</audio>
<div className="slider-wrapper">
<Slider
className="slider"
min={0}
max={100}
step={1}
value={audio.volume * 100}
onChange={(newValue) => handleSliderChange(newValue, index)}
vertical
/>
<p>{audio.volume * 100}%</p>
</div>
</div>
))}
</div>
</>
);
}
export default App;
Right now, I’m getting this error:
Error Invalid hook call. Hooks can only be called inside of the body
of a function component. This could happen for one of the following
reasons:
- You might have mismatching versions of React and the renderer (such as React DOM)
- You might be breaking the Rules of Hooks
- You might have more than one copy of React in the same app See https://reactjs.org/link/invalid-hook-call for tips about how to debug
and fix this problem.
I’m confused, I’m not calling hooks outside of a function component. What could the the problem and how to fix it?