APICloud平台使用融云模块实现音视频通话实践经验总结分享

简介: APICloud平台使用融云模块实现音视频通话实践经验总结分享

 需求概要:实现视频拨打、接听、挂断、视频界面大小窗口、点击小窗口实现大小窗口互换。

 

实现思路:一方拨打后,另一方要能收到相应事件,然后接听。接通后,渲染对方视频画面。那么己方视频画面什么时候渲染呢?对于呼叫方,可以在呼叫后开始渲染,也可以接通事件事件发生后再开始渲染。对于接通方可以在点击接听按钮后开始渲染,也可以在接通事件发生后开始渲染。

 

有了上述思路,在模块文档中查找相应api,编写代码,就可以验证我们的思路是否可以实现。如果遇到问题,再调整实现思路。

 

以下是融云模块文档链接:https://docs.apicloud.com/Client-API/Open-SDK/rongCloud2

简要介绍用到的主要API:

-startCall   发起音视频通话
-addCallReceiveListener  音视频来电事件监听
-accept 接听来电
-addCallSessionListener 音视频通话事件的监听(包含响铃、接通、挂断等多个事件监听)setVideoView  设置视频区域

-resetVideoView  重设视频区域

-removeVideoView  移除视频区域

-hangup 挂断

 

下面讲解代码。

要调用音视频通话功能前应先调用 api.hasPermission 接口检查是否有麦克风、相机权限,如果没有,要先申请权限。

api.requestPermission({
            list: ['microphone', 'camera', 'storage', 'photos'],
            code: 1
        })

image.gif

融云初始化成功之后,可添加相应事件的监听。didReceiveCall 接到来电事件后,弹出接听页面。接听后,会执行到 didConnect 事件, 此时可设置本地窗口 setVideoView ;稍后会执行到remoteUserDidJoin (对端用户加入通话事件),此时可以通过 setVideoView 设置对端用户窗口。通过videoViewBringToFront 接口将本地小窗口调整到最前方。

apiready = function () {
        rong = api.require('rongCloud2');
        rong.init({
            huaweiPush: false
        }, function (ret, err) {
            if (ret.status == 'error') {
                api.toast({
                    msg: err.code
                });
            } else {
                console.log('初始化成功');
                rong.setConnectionStatusListener(function (ret, err) {
                    console.log("连接状态监听:" + ret.result.connectionStatus);
                });
                //收到来电事件监听
                rong.addCallReceiveListener({
                    target: 'didReceiveCall'
                }, function (ret) {
                    console.log('didReceiveCall:' + JSON.stringify(ret))
                    callId = ret.callSession.callId;
                    api.toast({
                        msg: '来电请接听'
                    })
                    fnopenbtnframe();     //打开接听、挂断按钮所在的frame
                });
                // 通话连接成功监听
                rong.addCallSessionListener({
                    target: 'didConnect'    
                }, function (ret) {
                    console.log('didConnect:' + JSON.stringify(ret))
                    var myname = api.getPrefs({
                        sync: true,
                        key: 'myname'
                    });
                    //打开本地窗口
                    fnsetVideoView(api.winWidth - 200, 100, 160, 200, myname);
                    //将本地窗口显示到最前方
                    setTimeout(function () {
                        rong.videoViewBringToFront({
                            userId: myname
                        })
                    }, 1000)
                })
                //通话已结束的事件
                rong.addCallSessionListener({
                    target: 'didDisconnect'
                }, function (ret) {
                    console.log('didDisconnect:' + JSON.stringify(ret))
                })
                //对端用户加入了通话的事件
                rong.addCallSessionListener({
                    target: 'remoteUserDidJoin'
                }, function (ret) {
                    console.log("对端用户加入了通话的事件:" + JSON.stringify(ret));
                    var uid = ret.userId;
                    //设置远端窗口
                    fnsetVideoView(0, 0, api.winWidth, api.winHeight, uid);
                });
                //监听视频区域点击事件,实现大小窗口切换
                rong.addVideoViewListener(function (ret) {
                    //判断点击的是否是初始小窗口
                    if (ret.userId == myname && meissmall) {
                        fnresetVideoView(0, 0, api.winWidth, api.winHeight, ret.userId);
                        fnresetVideoView(api.winWidth - 200, 100, 160, 200, hename);
                        meissmall = false;
                        setTimeout(function () {
                            rong.videoViewBringToFront({
                                userId: hename
                            })
                        }, 1000)
                        setTimeout(function () {
                            fnopenbtnframe()
                        }, 1200)
                    }
                    if (ret.userId == hename && !meissmall) {
                        fnresetVideoView(0, 0, api.winWidth, api.winHeight, ret.userId);
                        fnresetVideoView(api.winWidth - 200, 100, 160, 200, myname);
                        meissmall = true;
                        setTimeout(function () {
                            rong.videoViewBringToFront({
                                userId: myname
                            })
                        }, 1000)
                        setTimeout(function () {
                            fnopenbtnframe()
                        }, 1200)
                    }
                })
            }
        });
    };

image.gif

实现效果如下:

08195207_eyBQ.png

 

其他经验总结:

返回错误码34001,重启loader可解决,可能换账号登录,wifi 同步重启loader 有缓存用户信息导致。

接听不到来电事件,可尝试用4g 网络测试。有些公司防火墙,或者电脑共享的wifi 热点网络有限制或不稳定。

 

以上经验都是无数次排错总结出来的,看了至少能帮你节省两个工作日。

 

最后贴下完整代码:

<!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport"
        content="maximum-scale=2.0,minimum-scale=1.0,user-scalable=1,width=device-width,initial-scale=1.0" />
    <meta name="format-detection" content="telephone=no,email=no,date=no,address=no">
    <title>Hello APP</title>
    <link rel="stylesheet" type="text/css" href="../css/api.css" />
    <script src="../script/sha1.js"></script>
    <style>
        body {
            margin-top: 90px;
        }
        button {
            padding: 10px
        }
    </style>
</head>
<body id="bd">
    <button onclick="fnrequestPermission()">fnrequestPermission</button>
    <input id="useName" placeholder="输入用户名" style="display: block" />
    <div id="stauseName" style="display: none">
        **用户已登录
    </div>
    <input id="fridendName" placeholder="输入好友用户名" style="" />
    <br>
    <button onclick="login()">
        登录
    </button>
    <br>
    <button onclick="fnstartCall()">
        fnstartCall
    </button>
    <br>
    <br><br>
    <p>
    <ul>
        <li>1. 测试步骤</li>
        <li>2. 准备两部手机A和B</li>
        <li>3. A手机在【输入用户名】【输入好友用户名】处分别输入a, b;然后点登录</li>
        <li>4. B手机在【输入用户名】【输入好友用户名】处分别输入b, a;然后点登录</li>
        <li>5. 一部手机点fnstartCall</li>
        <li>6. 另一部手机在弹出‘来电请接听提示后’,会弹出底部按钮frame,点击【接听】</li>
        <li>7. 接通后,弹出大小视频窗口。点击小窗口可实现切换。</li>
    </ul>
    </p>
</body>
<script type="text/javascript" src="../script/api.js"></script>
<script type="text/javascript">
    var rong;
    var myname = '';
    var hename = '';
    var meissmall = true;
    function fnrequestPermission() {
        api.requestPermission({
            list: ['microphone', 'camera', 'storage', 'photos'],
            code: 1
        })
    }
    apiready = function () {
        rong = api.require('rongCloud2');
        rong.init({
            huaweiPush: false
        }, function (ret, err) {
            if (ret.status == 'error') {
                api.toast({
                    msg: err.code
                });
            } else {
                console.log('初始化成功');
                rong.setConnectionStatusListener(function (ret, err) {
                    alert("setConnectionStatusListener::::::" + ret.result.connectionStatus);
                });
                rong.addCallReceiveListener({
                    target: 'didReceiveCall'
                }, function (ret) {
                    console.log('didReceiveCall:' + JSON.stringify(ret))
                    callId = ret.callSession.callId;
                    api.toast({
                        msg: '来电请接听'
                    })
                    fnopenbtnframe();
                });
                rong.addCallSessionListener({
                    target: 'didConnect'
                }, function (ret) {
                    console.log('didConnect:' + JSON.stringify(ret))
                    var myname = api.getPrefs({
                        sync: true,
                        key: 'myname'
                    });
                    //打开本地窗口
                    fnsetVideoView(api.winWidth - 200, 100, 160, 200, myname);
                    setTimeout(function () {
                        rong.videoViewBringToFront({
                            userId: myname
                        })
                    }, 1000)
                })
                rong.addCallSessionListener({
                    target: 'didDisconnect'
                }, function (ret) {
                    console.log('didDisconnect:' + JSON.stringify(ret))
                })
                rong.addCallSessionListener({
                    target: 'remoteUserDidJoin'
                }, function (ret) {
                    console.log("对端用户加入了通话的事件:" + JSON.stringify(ret));
                    var uid = ret.userId;
                    fnsetVideoView(0, 0, api.winWidth, api.winHeight, uid);
                });
                rong.addVideoViewListener(function (ret) {
                    //判断点击的是否是初始小窗口
                    if (ret.userId == myname && meissmall) {
                        fnresetVideoView(0, 0, api.winWidth, api.winHeight, ret.userId);
                        fnresetVideoView(api.winWidth - 200, 100, 160, 200, hename);
                        meissmall = false;
                        setTimeout(function () {
                            rong.videoViewBringToFront({
                                userId: hename
                            })
                        }, 1000)
                        setTimeout(function () {
                            fnopenbtnframe()
                        }, 1200)
                    }
                    if (ret.userId == hename && !meissmall) {
                        fnresetVideoView(0, 0, api.winWidth, api.winHeight, ret.userId);
                        fnresetVideoView(api.winWidth - 200, 100, 160, 200, myname);
                        meissmall = true;
                        setTimeout(function () {
                            rong.videoViewBringToFront({
                                userId: myname
                            })
                        }, 1000)
                        setTimeout(function () {
                            fnopenbtnframe()
                        }, 1200)
                    }
                })
            }
        });
    };
    //打开视频区域
    function fnsetVideoView(x, y, w, h, uid) {
        rong.setVideoView({
            rect: {
                x: x,
                y: y,
                w: w,
                h: h
            },
            userId: uid,
            bg: '#ff0000',
            renderModel: 'fit',
            fixedOn: '',
            fixed: false
        });
    }
    function fnresetVideoView(x, y, w, h, uid) {
        rong.resetVideoView({
            rect: {
                x: x,
                y: y,
                w: w,
                h: h
            },
            userId: uid,
            bg: '#ff0000',
            renderModel: 'fit'
        });
    }
    //移除视频区域
    function fnremoveVideoView(ruid) {
        rong.removeVideoView({
            userId: ruid
        });
    }
    function fnstartCall() {
        myname = api.getPrefs({
            sync: true,
            key: 'myname'
        });
        hename = api.getPrefs({
            sync: true,
            key: 'hename'
        });
        rong.startCall({
            targetId: hename,
            mediaType: 'video',
            conversationType: 'PRIVATE',
            userIdList: [hename]
        }, function (ret) {
            console.log('startCall:' + JSON.stringify(ret))
            callId = ret.callSession.callId;
        });
        fnopenbtnframe();
    }
    //打开按钮页面
    function fnopenbtnframe() {
        api.openFrame({
            name: 'btframe',
            url: 'button.html',
            rect: {
                marginLeft: 0,
                marginBottom: 0,
                h: 100,
                w: 'auto'
            }
        })
    }
    function fnaccept() {
        //同步返回结果:
        myname = api.getPrefs({
            sync: true,
            key: 'myname'
        });
        hename = api.getPrefs({
            sync: true,
            key: 'hename'
        });
        rong.accept({
            mediaType: 'video',
            callId: callId
        });
    }
    function fnhangup() {
        rong.hangup();
        fnremoveVideoView(hename);
        fnremoveVideoView(myname);
        api.closeFrame({
            name: 'btframe'
        })
    }
    function fngetCallSession() {
        rong.getCallSession(function (ret) {
            api.alert({
                msg: JSON.stringify(ret)
            });
        });
    }
    //请求token
    function login() {
        var now = new Date();
        var number = now.getSeconds();
        //这将产生一个基于目前时间的0到59的整数。
        var timestamp = Date.parse(new Date());
        timestamp = timestamp / 1000;
        var AppKey = "pwe86ga5p****"; //填写自己的参数
        var appSecret = "Eo1hnmggH****"; //填写自己的参数
        var Nonce = number;
        var Timestamp = timestamp;
        var Signature = SHA1(appSecret + Nonce + Timestamp);
        var uid = document.getElementById('useName').value;
        var uid2 = document.getElementById('fridendName').value;
        api.setPrefs({
            key: 'myname',
            value: uid
        })
        api.setPrefs({
            key: 'hename',
            value: uid2
        })
        api.ajax({
            url: 'http://api.cn.ronghub.com/user/getToken.json',
            method: 'post',
            headers: {
                "Content-Type": "Application/x-www-form-urlencoded",
                "App-Key": AppKey,
                "Nonce": Nonce,
                "Timestamp": Timestamp,
                "Signature": Signature
            },
            data: {
                'values': {
                    userId: uid,
                    name: uid,
                }
            }
        }, function (ret, err) {
            if (ret) {
                token = ret.token;
                connect();
                var labelUsename = document.getElementById('stauseName');
                labelUsename.style.display = "block";
                labelUsename.innerHTML = uid + "已登录";
            } else {
                api.alert({
                    msg: JSON.stringify(err)
                });
            }
        })
    }
    function logout() {
        rong.logout(function (ret, err) {
            console.log(JSON.stringify(ret));
            if (ret.status == 'error')
                api.toast({
                    msg: err.code
                });
        });
    }
    function connect() {
        rong.connect({
            token: token
        }, function (ret, err) {
            if (ret.status == 'success') {
                console.log(ret.result.userId);
            } else {
                console.log(err.code)
            }
        });
    }
    function getConnectionStatus() {
        rong.getConnectionStatus(function (ret, err) {
            api.toast({
                msg: ret.result.connectionStatus
            });
        })
    }
</script>
</html>


目录
相关文章
|
API PHP 开发者
周边地点搜索免费API接口详解
周边地点搜索API由接口盒子提供,支持基于经纬度搜索周边POI信息,涵盖公交站、酒店、餐厅等。具备多类型筛选、自定义半径(最大10公里)、分页查询等功能,返回数据包含地址、距离、坐标及公交线路详情,适用于各类位置服务应用。
822 1
|
3月前
|
人工智能 IDE API
2026百炼Token Plan完整指南:个人/企业套餐、Credits计费、API调用实操全解析
随着AI应用开发、智能体Agent工具的普及,大量开发者和团队长期高频调用各类大模型。传统按量按Token计费模式下,多轮Agent任务、长文档处理、多模态生成很容易造成月度账单剧烈波动,预算很难提前规划。百炼Token Plan是面向个人开发者、工作室与企业团队推出的包月订阅式AI模型调用服务,统一使用Credits作为用量计量单位,一份订阅额度可以调用文本、图像、视频、多模态等多款主流模型,同时原生兼容Cursor、Codex、OpenClaw等大量主流编程与智能体工具。相比直接按量API调用,订阅模式综合调用成本更低,并且拥有夜间时段抵扣折扣。本文完整讲解产品定位、个人版与企业版套餐档位
1520 0
|
机器学习/深度学习 算法 数据可视化
YOLO26如何训练自己的分割数据集 | (裂缝分割为案列)
YOLO26全新发布!本文详解其核心创新:移除DFL、端到端无NMS推理、ProgLoss+STAL损失策略、MuSGD优化器,并附结构框图;同时以裂缝分割为例,手把手演示自定义数据集训练全流程(含预训练与非预训练对比)。
896 0
|
8月前
|
索引 Python Windows
别再手动调PPT了:用Python批量生成文本框,还能自动排版
小张苦于每周手动制作PPT周报。本文介绍如何用Python库`python-pptx`自动化生成格式统一的周报:从创建文本框、精细控制字体/颜色/对齐,到实现多级列表、模板占位符替换,助运营人员告别重复劳动,5分钟搞定周报。(239字)
822 0
|
8月前
|
人工智能 语音技术 云计算
阿里云 AI 加持书尖 AI 实测:海量书库与 AI 听书新体验对比喜马拉雅
在阿里云AI赋能下,书尖AI实测展现三大优势:1.2亿册全品类书库;首创双人互动式AI播客解读;2分钟极速生成书籍精华。相较喜马拉雅,其AI定制化、知识提炼与沉浸听书体验更胜一筹,是高效智能阅读新选择。(239字)
|
10月前
|
人工智能 运维 前端开发
GLM-5深夜官宣:Pony Alpha身份揭晓,编程能力逼近Claude Opus
刚发完DeepSeek V4,智谱又来搞事情。 今天是老金我写的 第三篇文章,手都快敲断了。 但这个消息不写不行——GLM-5 正式(偷摸地)发布了。 2月11日深夜,智谱AI官宣新一代旗舰大模型GLM-5。 之前在OpenRouter上神秘出现的"Pony Alpha",身份终于揭晓。 据DoNews报道:Pony Alpha就是GLM-5的低调测试版。 ![Image](https://u
966 25
|
10月前
|
数据采集 监控 机器人
实战!用Scrapy+Flask构建京东商品比价微信机器人
本项目是一个基于微信的京东智能比价机器人,集成Scrapy+Selenium爬虫、Flask API与itchat/Wechaty微信服务,支持商品搜索、实时比价、30天价格趋势分析、降价自动预警及收藏管理,全栈可部署(Docker+Nginx),助力用户省钱决策。(239字)
|
11月前
|
JavaScript 算法 网络协议
在阿里云申请了SSL证书后怎么安装?在Node.js环境安装SSL证书教程指导
本文详细介绍了在阿里云轻量应用服务器部署Node.js环境并启用HTTPS加密访问的全流程。内容涵盖前提条件(域名备案、解析)、SSL证书申请(免费与付费选项)、证书配置及服务器端代码编写等步骤。
677 4
|
自然语言处理 安全
Min-p采样:通过动态调整截断阈值让大模型文本生成兼顾创造力与逻辑性
大语言模型通过预测下一个词生成文本,采样策略决定其创造力与连贯性。Min-p采样根据模型置信度动态调整选择阈值,在高不确定性时扩大候选范围,低不确定性时聚焦高概率词,相较Top-k、Top-p等方法,更好平衡了多样性与质量,尤其在高温下仍保持输出稳定,提升生成文本的流畅性与创新性。
678 3
|
9月前
|
人工智能 搜索推荐 Linux
OpenClaw能做什么?OpenClaw阿里云/本地保姆级部署流程+自定义 Skill 技能开发及避坑终极手册
“OpenClaw的真正威力,藏在Skills系统里”——这是2026年所有资深用户的共识。作为开源AI智能体框架,OpenClaw的基础对话功能仅能满足沟通需求,而Skills(技能)系统才是让它从“能说会道”变身“能说会做”的核心:无论是查询天气、处理PDF、生成图表,还是自动化办公、代码开发,都能通过技能实现。
1632 1