Roee Angel
Roee Angel

Reputation: 201

How to set audio volume using React and Twilio?

I am using Twilio for streaming audio and video, and I want to be able to control the audio volume using React instead of using the document.getElementById('audio') method. Currently, I have the following code which sets the audio volume based on a value from guide.liveDetails.volume:

 useEffect(() => {
        const audioTrack = audioTracks[0];
        const audio = document.getElementById('audio');
        audio.volume = (guide.liveDetails.volume / 100);
        if (audioTrack && mic) {
            audioTrack.attach(audioRef.current);
            return () => {
                audioTrack.detach();
            };
        }
    }, [audioTracks, mic, guide]);

  return (
        <>
            {camera && <video ref={videoRef} autoPlay={true} />}
            <audio id="audio" ref={audioRef} autoPlay={true} muted={!mic} />
        </>
    );

However, I want to know how to set the volume using React instead of using document.getElementById('audio'). Any help would be appreciated!

Upvotes: 0

Views: 4797

Answers (1)

Surjeet Bhadauriya
Surjeet Bhadauriya

Reputation: 7156

You can use useRef instead of document as shown below

const audioRef = useRef(); // on the top of your function component

and then use audioRef to access the element.

audioRef.current.volume // use this where you want

Upvotes: 3

Related Questions