react中如何调用腾讯api接口来实现视频通话

开发环境要求:

  •   React ≥ v18.0。
  •   webpack 版本:webpack ≥ 5.0.0。
  •   Node.js 版本:Node.js ≥ 12.13.0(推荐使用官方 LTS 版本,npm 版本请与 node 版本匹配)
  •   Modern browser, supporting WebRTC APIs.(WebRTC(Web 实时通信)是一种使 Web 应用程序和站点能够捕获和选择性地流式传输音频或视频媒体,以及在浏览器之间交换任意数据的而无需中间件的技术。WebRTC 的一系列标准使得在不需要用户安装插件或任何其他第三方软件的情况下,可以实现点对点数据共享和电话会议)

步骤一:开通服务

        在使用腾讯云提供的音视频服务前,需要前往腾讯api的控制台,为应用开通音视频服务。

   

点击实时音视频进入之后按照步骤一步一步做即可,开通了音视频服务之后在往下走。

步骤二:创建项目

1. 如果您尚未安装 create-react-app ,可以在 terminal 或 cmd 中采用如下方式进行安装:

npm install -g create-react-app

 2.创建一个新的 React 项目,您可自行选择是否需要使用 ts 模板。

npx create-react-app tuicallkit-demo --template typescript

3.创建项目完成后,切换到项目所在目录。

cd tuicallkit-demo

步骤三:下载 TUICallKit 组件

1. 通过 npm 方式下载 @tencentcloud/call-uikit-react组件并在项目中使用。

TUICallKit是基于通话场景深度定制的一款产品,提供微信视频聊天同款 UI 组件,仅需3步,最快1天上线,可节省90%开发时间。 支持小程序、 iOS、Android、Web、uni-app、Flutter 等平台全球互通。

npm install @tencentcloud/call-uikit-react

2.将 debug 目录复制到您的项目目录 tuicallkit-demo/src。

GenerateTestUserSig的开源模块可以帮忙您快速生成 UserSig。 您只需设置 SDKAPPID(应用 SDKAppID)、EXPIRETIME(UserSig 过期时间)和 SECRETKEY(密钥信息)三个成员变量的取值,然后调用 genTestUserSig () 函数即可快速获取 UserSig (UserSig 是腾讯云设计的一种安全保护签名,目的是为了阻止恶意攻击者盗用您的云服务使用权。 目前,腾讯云的游戏多媒体引擎3.0(GME 3.0)、实时音视频(TRTC)、即时通信(IM)、以及移动直播(MLVB)等服务都采用了该套安全保护机制)

import * as GenerateTestUserSig from "../../../node_modules/@tencentcloud/call-uikit-react/debug/GenerateTestUserSig-es";

步骤四:引入 TUICallKit 组件

1. 如下代码示例中的 SDKAppID、SecretKey 、userID、callUserID 四个参数。

        SDKAppID:在腾讯云创建的音视频应用 SDKAppID

        SecretKey:用户签名

        userID:主叫的 userID,字符串类型,只允许包含英文字母(a-z 和 A-Z)、数字(0-9)、连词符(-)和下划线(_)。

        callUserID:被叫的 userID,需要已初始化存在。(demo 中的 callUserID,当有被叫时输入,无被叫可以不输入)。

2. 在 tuicallkit-demo/src/jsx 中引入下面代码。

// 视频通话,祖传代码勿动!!!!!
import React, { useState, useMemo, useEffect } from "react";
import { TUICallKit, TUICallKitServer, TUIGlobal } from "@tencentcloud/call-uikit-react";
import * as GenerateTestUserSig from "../../../node_modules/@tencentcloud/call-uikit-react/debug/GenerateTestUserSig-es";
import './APP.css'
export default function XXXX() {

    // 视频通话使用到的状态
    const [userData, setUserData] = useState({
        userID: "", 
        callUserID: "", 
        SDKAppID: '',        // Replace with your SDKAppID  腾讯api 实时通信中的的SDKAppID 
        SecretKey: "",      // Replace with your SecretKey 腾讯api 实时通信中的的SDKAppkey
        isLogin: false,   //控制是否登录
    });


    // 设置当前使用人员联系方式,用于发起视频通话,可以注释,注释之后需要手动设置自己的联系方式之后,才能进行视频通话
    useEffect(() => {
        setUserData((pr) => {
            return {
                ...pr,
                userID: JSON.parse(localStorage.getItem('usedata')).phone,
                isLogin: true
            }
        })
    }, [])



    // 设置自己的联系方式,用于发起视频通话,如果上面的useEffect没有注释,则这一段代码用不到,
    const init = async () => {
        const { SDKAppID, SecretKey, userID } = userData;  //获取SDKAppID,SecretKey,userID
        if (SDKAppID && SecretKey && userID) {             //验证是否已经设置好SDKAppID,SecretKey,userID
            try {
                await login(SDKAppID, SecretKey, userID);  //触发login方法
                setUserData((prevState) => ({
                    ...prevState,
                    isLogin: true,
                }));
                alert("[TUICallKit] 设置本人联系方式成功.可以进行视频聊天了");
            } catch (error) {
                console.error(error);
            }
        } else {
            alert("[TUICallKit] 请填写 SDKAppID, userID 和 SecretKey.");
        }
    };


    const login = async (SDKAppID, SecretKey, userId) => {
        const { userSig } = GenerateTestUserSig.genTestUserSig({
            userID: userId,
            SDKAppID: Number(SDKAppID),
            SecretKey: SecretKey,
        });
        await TUICallKitServer.init({ //【1】初始化TUICallKit组件 
            userID: userId,
            userSig,
            SDKAppID: Number(SDKAppID),
        });
    };



    
    const call = async () => {
        const { SDKAppID, SecretKey, userID } = userData;
        await login(SDKAppID, SecretKey, userID);
        await TUICallKitServer.call({ userID: userData.callUserID, type: 2 }); //【2】进行1v1视频通话
    };




    const callKitStyle = useMemo(() => {
        if (TUIGlobal.isPC) {
            return { width: '100%', height: '100%', margin: '0 auto' }; //接听页面样式
        }
        return { width: '100%', height: window.innerHeight }; //发起聊天页面样式
    }, [TUIGlobal.isPC]);



    return (
        <div className="liaotian">
            <TUICallKit style={callKitStyle}></TUICallKit>
            {/* <h4> {userData.isLogin ? "Call Panel" : "Login Panel"} </h4>   根据当前isLogin状态的不同显示不同的标题 */}
            <h1 style={{ marginTop: '20%', marginBottom: '20%' }}>联络感情</h1>
            <div>
                <div style={{marginBottom:'20%'}}>
                    <input
                        className="input1"
                        value={userData.isLogin ? userData.callUserID : userData.userID}
                        onChange={(value) => {
                            const key = userData.isLogin ? "callUserID" : "userID";
                            setUserData((prevState) => ({
                                ...prevState,
                                [key]: value.target.value,
                            }));
                        }}
                        style={{ width: 230, margin: '0 auto' }}
                        placeholder={
                            userData.isLogin ? "请输入对方的联系方式" : "请输入您的联系方式"
                        }
                    />
                    <button className="" onClick={userData.isLogin ? call : init}> {userData.isLogin ? "拨打电话" : "设置联系方式"} </button>
                </div>
                <p style={{ margin: '10' }}> {userData.isLogin ? `您当前的联系方式:  ${userData.userID}` : ""} </p>
            </div>
        </div>
    )

}

步骤五:拨打您的第一通电话

1. 在终端输 npm run start 运行 我们创建的tuicallkit-demo项目。

2.输入登录的 userID,点击 login 按钮,弹出 login success 表示初始化成功。

3.输入被叫的 userID,点击 call 按钮,发起 1v1 视频通话。

React项目引入Ant Design并集成腾讯地图(Tencent Map)可以分为以下几个步骤: 1. **安装依赖**: 首先,你需要安装`antd`库,如果你还没有安装,可以使用`npm`或`yarn`来安装: ``` npm install antd @tencent mapbox-gl-js // 或者 yarn add antd tencent-map ``` 2. **配置腾讯地图API**: 腾讯地图通常需要一个Key来进行地图功能的访问,注册并在官网申请一个地图API Key。将其放在项目的环境变量或者配置文件。 3. **引入组件**: 在React组件,导入需要的地图组件,比如`Map`: ```jsx import { Map } from '@ant-design/pro-components'; // 这里使用了Pro Components版本,如果是基础版则import从'tencent-map' ``` 4. **初始化地图**: 创建地图实例,并设置初始位置和缩放级别: ```jsx const initialLocation = { latitude: 39.9042, longitude: 116.4074 }; // 北京坐标作为示例 const mapConfig = { center: initialLocation, zoom: 11, }; const mapRef = useRef(null); function handleMapReady(mapInstance) { mapInstance.setCenter(initialLocation.longitude, initialLocation.latitude); // 设置心点 } return ( <div> <Map ref={mapRef} init={handleMapReady} mapStyle="dark" /> </div> ); ``` 5. **地点查询**: 使用腾讯地图提供的`Marker`组件标记特定地点,然后通过事件监听来处理查询: ```jsx const markerRef = useRef(null); useEffect(() => { if (markerRef.current) { markerRef.current.openInfoWindow({ content: '北京', }); } }, [markerRef]); const onSearch = async (keyword) => { const geocoder = new window.Tencent.maps.Geocoder(); try { const result = await geocoder.geocode({ key: 'your_api_key', location: keyword }); if (result && result.regeocode.addressComponent) { // 根据结果更新地图标记位置 const newLocation = result.regeocode.formattedAddress; setMarkerPosition(result.regeocode.location); } } catch (error) { console.error('Geocode failed:', error); } }; // 地图上添加点击事件监听地点查询 mapRef.current.on('click', () => { onSearch('输入您想查询的地址'); }); ``` 这里的`setMarkerPosition`用于设置`Marker`的位置。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值