0

我正在 React 中为客户端创建视频通话应用程序。要求是仅将 Agora SDK 用于直播和视频通话。出于演示和测试的目的,从一些来源获得了示例代码,后来使用我自己创建的 App_ID 并申请连接,但是,意外无法运行。为了将 React 应用程序连接到 Agora SDK,有什么更好的解决方案。如果有的话,请提供相同的来源。

以下是供参考的代码

const [joined, setJoined] = useState(false);

    const channelRef = useRef("");
    const remoteRef = useRef("");
    const leaveRef = useRef("");

    const loadCert = async () => {
        // create a certificate authority
        const ca = await mkcert.createCA({
            organization: 'Hello CA',
            countryCode: 'NP',
            state: 'Bagmati',
            locality: 'Kathmandu',
            validityDays: 365
        });

        // then create a tls certificate
        const cert = await mkcert.createCert({
            domains: ['127.0.0.1', 'localhost'],
            validityDays: 365,
            caKey: ca.key,
            caCert: ca.cert
        });

        console.log(cert.key, cert.cert); // certificate info
        console.log(`${cert.cert}\n${ca.cert}`); // create a full chain certificate by merging CA and domain certificates
    }

    async function handleSubmit(e) {
        try {
            if (channelRef.current.value === "") {
                return console.log("Please Enter Channel Name");
            }
            setJoined(true);


            rtc.client = AgoraRTC.createClient({ mode: "rtc", codec: "h264" });


            const uid = await rtc.client.join(
                options.appId,
                channelRef.current.value,
                options.token || null,
                null
            );

            // Create an audio track from the audio captured by a microphone
            rtc.localAudioTrack = await AgoraRTC.createMicrophoneAudioTrack();

            // Create a video track from the video captured by a camera
            rtc.localVideoTrack = await AgoraRTC.createCameraVideoTrack();
            // Play localStream
            rtc.localVideoTrack.play("local-stream");

            rtc.client.on("user-published", async (user, mediaType) => {
                // Subscribe to a remote user
                await rtc.client.subscribe(user);
                console.log("subscribe success");
                // console.log(user);

                if (mediaType === "video" || mediaType === "all") {
                    // Get `RemoteVideoTrack` in the `user` object.
                    const remoteVideoTrack = user.videoTrack;
                    console.log(remoteVideoTrack);

                    // Dynamically create a container in the form of a DIV element for playing the remote video track.
                    const PlayerContainer = React.createElement("div", {
                        id: user.uid,
                        className: "stream",
                    });
                    ReactDOM.render(
                        PlayerContainer,
                        document.getElementById("remote-stream")
                    );

                    user.videoTrack.play(`${user.uid}`);
                }

                if (mediaType === "audio" || mediaType === "all") {
                    // Get `RemoteAudioTrack` in the `user` object.
                    const remoteAudioTrack = user.audioTrack;
                    // Play the audio track. Do not need to pass any DOM element
                    remoteAudioTrack.play();
                }
            });

            rtc.client.on("user-unpublished", async (user) => {
                // Get the dynamically created DIV container
                const playerContainer = document.getElementById(user.uid);
                console.log(playerContainer);

                await rtc.client.publish([rtc.localAudioTrack, rtc.localVideoTrack]);
                console.log('[publish success');
            });

        }
        catch (err) {
            console.error(err)
        }
    }

    async function handleLeave() {
        try {
            const localContainer = document.getElementById("local-stream");

            rtc.localAudioTrack.close();
            rtc.localVideoTrack.close();

            setJoined(false);
            localContainer.textContent = "";

            // Traverse all remote users
            rtc.client.remoteUsers.forEach((user) => {
                // Destroy the dynamically created DIV container
                const playerContainer = document.getElementById(user.uid);
                playerContainer && playerContainer.remove();
            });

            // Leave the channel
            await rtc.client.leave();
        } catch (err) {
            console.error(err);
        }
    }

    useEffect(() => {
        loadCert()
    }, [])


    return (
        <div>
            <div className="container">
                <input
                    type="text"
                    ref={channelRef}
                    id="channel"
                    placeholder="Enter Channel name"
                />
                <input
                    type="submit"
                    value="Join"
                    onClick={handleSubmit}
                    disabled={joined ? true : false}
                />
                <input
                    type="button"
                    ref={leaveRef}
                    value="Leave"
                    onClick={handleLeave}
                    disabled={joined ? false : true}
                />
            </div>
            {joined ? (
                <>
                    <div id="local-stream" className="stream local-stream"></div>
                    <div
                        id="remote-stream"
                        ref={remoteRef}
                        className="stream remote-stream"
                    ></div>
                </>
            ) : null}
        </div>
    );
};

在此处输入图像描述

为高效运行 App 需要进行哪些更改

4

0 回答 0