I need some help on how I can update the DOM audio in real time.
I'm trying to make the audio muted and unmuted based on the user preference,
The recording is saved in the public folder.
The audio is working fine on the first load if you set mute to be true or false, then when you try to change it, the mute props do not update.
Here is a short sample of my code, I'm using next.js.
import { RECORDING } from '@/constants/media.constant';
import { useEffect, useState } from 'react';
function Sample() {
const [mute, setMute] = useState(false);
useEffect(() => {
(() => playWithAudio())();
}, []);
const playWithAudio = () => {
const tryToPlay = setInterval(() => {
// audio recording, format mp3
const audio = new Audio(RECORDING.HELLO);
audio.loop = true;
audio.muted = mute;
audio
.play()
.then(() => {
clearInterval(tryToPlay);
})
.catch(() => console.info('User has not interacted with DOM yet.'));
}, 1000);
};
return (
<>
<button onClick={() => setMute(!mute)}>Click</button>
</>
);
}
export default Sample;
Any help would be appreciated.
CodePudding user response:
Give this a try
import { useEffect, useState } from "react";
import { RECORDING } from "@/constants/media.constant";
function Sample() {
const [mute, setMute] = useState(false);
const [audio, setAudio] = useState(null);
useEffect(() => {
setAudio(new Audio(RECORDING.HELLO));
}, []);
useEffect(() => {
if (audio) playWithAudio();
}, [audio]);
const playWithAudio = () => {
const tryToPlay = setInterval(() => {
// audio recording, format mp3
audio.loop = true;
audio.muted = mute;
audio
.play()
.then(() => {
clearInterval(tryToPlay);
})
.catch(() => console.info("User has not interacted with DOM yet."));
}, 1000);
};
return (
<>
<button
onClick={() => {
if (audio) audio.muted = !mute;
setMute(!mute);
}}
>
{mute ? "UnMute" : "Mute"}
</button>
</>
);
}
export default Sample;