Apiccloud platform uses rongyun module to summarize and share the practical experience of audio and video calls

Posted by merebel on Tue, 08 Mar 2022 13:23:22 +0100

Demand summary: realize video dialing, answering, hanging up, video interface size window and click small window to realize the exchange of size window.

Implementation idea: after one party dials, the other party should be able to receive the corresponding event and then answer. When connected, render the video picture of the other party. When will your video be rendered? For the caller, you can start rendering after the call, or you can connect the event and start rendering after the event occurs. For the connected party, you can start rendering after clicking the answer button, or you can start rendering after the connection event occurs.

With the above ideas, find the corresponding api in the module document and write code to verify whether our ideas can be realized. If you encounter problems, adjust the implementation idea.

The following is the link to the rongyun module document: https://docs.apicloud.com/Cli...

Briefly introduce the main API s used:

**startCall initiates an audio and video call
addCallReceiveListener # audio and video incoming call event monitoring
accept incoming call
addCallSessionListener monitoring of audio and video call events (including multiple event monitoring such as ringing, connecting and hanging up) setVideoView , set the video area
resetVideoView reset video area
removeVideoView remove video area
hangup hang up**

Here's the code.

Call API before calling audio and video call function The haspermission interface checks whether there are microphone and camera permissions. If not, apply for permissions first.

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

After rongyun is initialized successfully, you can add listening for corresponding events. didReceiveCall pops up the answer page after receiving the incoming call event. After answering, the didConnect event will be executed. At this time, you can set the local window {setVideoView; It will be executed to remoteUserDidJoin (opposite end user joins the call event) later. At this time, you can set the opposite end user window through {setVideoView. Adjust the local small window to the front through the videoviewbringtorfront interface.

 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('Initialization succeeded');

                rong.setConnectionStatusListener(function (ret, err) {
                    console.log("Connection status monitoring:" + ret.result.connectionStatus);
                });

                //Incoming call event monitoring
                rong.addCallReceiveListener({
                    target: 'didReceiveCall'
                }, function (ret) {
                    console.log('didReceiveCall:' + JSON.stringify(ret))
                    callId = ret.callSession.callId;
                    api.toast({
                        msg: 'Please answer the call'
                    })

                    fnopenbtnframe();     //Open the frame where the answer and end buttons are located
                });

                // Successful call connection monitoring

                rong.addCallSessionListener({
                    target: 'didConnect'    
                }, function (ret) {
                    console.log('didConnect:' + JSON.stringify(ret))

                    var myname = api.getPrefs({
                        sync: true,
                        key: 'myname'
                    });

                    //Open local window
                    fnsetVideoView(api.winWidth - 200, 100, 160, 200, myname);

                    //Displays the local window to the front
                    setTimeout(function () {
                        rong.videoViewBringToFront({
                            userId: myname
                        })
                    }, 1000)
                })
                
                //End of call event
                rong.addCallSessionListener({
                    target: 'didDisconnect'
                }, function (ret) {
                    console.log('didDisconnect:' + JSON.stringify(ret))
                })

                //The event that the opposite end user joins the call
                rong.addCallSessionListener({
                    target: 'remoteUserDidJoin'
                }, function (ret) {
                    console.log("The event that the opposite end user joins the call:" + JSON.stringify(ret));
                    var uid = ret.userId;
                    //Set remote window
                    fnsetVideoView(0, 0, api.winWidth, api.winHeight, uid);

                });


                //Monitor click events in the video area to switch between large and small windows
                rong.addVideoViewListener(function (ret) {

                    //Judge whether the clicked is the initial small window
                    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)

                    }

                })

               
            }
        });
    };

The results are as follows:

Other experience summary:

The error code 34001 is returned, which can be solved by restarting the loader. It may be caused by changing the account to log in, wifi synchronous restarting the loader and caching the user information.

If you can't answer an incoming call, you can try 4g network test. Some corporate firewalls or wifi hotspot networks shared by computers are limited or unstable.

The above experience is summed up by troubleshooting countless times. Reading it can help you save at least two working days.

Finally, paste the complete code:

<!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="enter one user name" style="display: block" />
    <div id="stauseName" style="display: none">
        **User logged in
    </div>
    <input id="fridendName" placeholder="Enter a friend user name" style="" />
    <br>
    <button onclick="login()">
        Sign in
    </button>
    <br>
    <button onclick="fnstartCall()">
        fnstartCall
    </button>
    <br>
    <br><br>
    <p>
    <ul>
        <li>1. testing procedure</li>
        <li>2. Prepare two mobile phones A and B</li>
        <li>3. A Enter the user name in [enter user name] and [enter friend user name] respectively a, b;Then click login</li>
        <li>4. B Enter the user name in [enter user name] and [enter friend user name] respectively b, a;Then click login</li>
        <li>5. A mobile phone point fnstartCall</li>
        <li>6. Another phone is popping up'Please answer the call after the prompt',The bottom button pops up frame,Click [answer]</li>
        <li>7. When connected, a large and small video window will pop up. Click the small window to switch.</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('Initialization succeeded');

                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: 'Please answer the call'
                    })
                    fnopenbtnframe();
                });

                rong.addCallSessionListener({
                    target: 'didConnect'
                }, function (ret) {
                    console.log('didConnect:' + JSON.stringify(ret))

                    var myname = api.getPrefs({
                        sync: true,
                        key: 'myname'
                    });
                    //Open local window
                    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("The event that the opposite end user joins the call:" + JSON.stringify(ret));
                    var uid = ret.userId;
                    fnsetVideoView(0, 0, api.winWidth, api.winHeight, uid);

                });


                rong.addVideoViewListener(function (ret) {

                    //Judge whether the clicked is the initial small window
                    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)

                    }

                })

               
            }
        });
    };

    //Open video area
    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'
        });
    }


    //Remove video area
    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();

    }

    //Open button page
    function fnopenbtnframe() {
        api.openFrame({
            name: 'btframe',
            url: 'button.html',
            rect: {
                marginLeft: 0,
                marginBottom: 0,
                h: 100,
                w: 'auto'
            }
        })
    }

    function fnaccept() {
        //Synchronization return result:
        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)
            });
        });
    }

    //Request token
    function login() {
        var now = new Date();
        var number = now.getSeconds();
        //This will produce an integer from 0 to 59 based on the current time.
        var timestamp = Date.parse(new Date());
        timestamp = timestamp / 1000;
        var AppKey = "pwe86ga5p****"; //Fill in your own parameters
        var appSecret = "Eo1hnmggH****"; //Fill in your own parameters
        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 + "Logged in";
            } 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>

Topics: iOS Android apicloud