如何有多个人可以加入同一频道,以便我们在Agora Android中拥有两个远程视图和一个本地视图?

如何解决如何有多个人可以加入同一频道,以便我们在Agora Android中拥有两个远程视图和一个本地视图?

我正在将Agora用于视频通话功能。我已针对1-1视频通话运行agora的示例代码,引用了此代码-https://docs.agora.io/en/Video/start_call_android?platform=Android

在示例中,我们有一个本地视图和一个远程视图,这很好用。现在,我想显示两个远程视图和一个本地视图。为此,我创建了具有两个远程视图和一个本地视图的布局。

也在onFirstRemoteVideoDecoded方法中,我检查是否添加了第一个远程视图,然后设置了第一个远程视图,否则设置了第二个远程视图。留给用户时,它与onUserOffline相同。我检查了是否记录了运行方法onRemoteUserLeft()或onRemoteUserLeft1()的第一个远程视图,该方法删除了相关视图。

要加入该频道,我提供了相同的频道名称和不同的令牌

`

var token1: String? = ("<token-string>")
    if (token1!!.isEmpty()) {
            token1 = null
    }
    mRtcEngine!!.joinChannel(
        token1,"67124678","null",0
        )

我有一个提供频道名称和相关令牌的链接。 https://mobile.quirkysemicolon.com/getTokens.php

我对如何在应用程序中使用此链接来加入同一频道上的多个用户感到困惑。

有人可以建议我如何实现此功能吗?

这是我的布局:

    <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <FrameLayout
        android:id="@+id/remote_video_view_container"
        android:layout_width="0dp"
        android:layout_height="284dp"
        android:layout_alignParentTop="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:background="@android:color/darker_gray"
        app:layout_constraintEnd_toStartOf="@+id/remote1_video_view_container"
        app:layout_constraintHorizontal_chainStyle="spread_inside"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />


    <FrameLayout
        android:id="@+id/remote1_video_view_container"
        android:layout_width="0dp"
        android:layout_height="284dp"
        android:layout_alignParentTop="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:background="@android:color/darker_gray"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/remote_video_view_container"
        app:layout_constraintTop_toTopOf="parent" />

    <FrameLayout
        android:id="@+id/local_video_view_container"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:background="@android:color/white"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/container"
        app:layout_constraintTop_toBottomOf="@+id/remote1_video_view_container" />

    <RelativeLayout
        android:id="@+id/container"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:background="@android:color/white"
        android:padding="20dp"

        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/local_video_view_container"
        app:layout_constraintHorizontal_chainStyle="spread_inside"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/remote1_video_view_container">


        <TextView
            android:id="@+id/textView2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:layout_alignParentRight="true"
            android:layout_gravity="center_horizontal"
            android:layout_marginTop="20dp"
            android:textSize="18sp"
            android:textColor="@android:color/black"
            android:text="Channel :" />

        <Button
            android:id="@+id/button"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Start"
            android:textColor="@android:color/white"
            android:background="@android:color/holo_green_dark"
            android:layout_marginTop="20dp"
            android:layout_gravity="center_horizontal"
            android:layout_below="@id/textView2"/>

        <Button
            android:id="@+id/button2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="End"
            android:onClick="onEndCallClicked"
            android:textColor="@android:color/white"
            android:background="@android:color/holo_red_dark"
            android:layout_marginTop="20dp"
            android:layout_gravity="center_horizontal"
            android:layout_below="@id/button"/>

        <TextView
            android:id="@+id/textView5"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/button2"
            android:layout_marginTop="20dp"
            android:textSize="18sp"
            android:textColor="@android:color/black"
            android:layout_gravity="center_horizontal"
            android:text="Token(Push Notify) : " />

    </RelativeLayout>


</androidx.constraintlayout.widget.ConstraintLayout>

这是我的活动

class MultipleRemoteViewActivity: AppCompatActivity() {

    private var mRtcEngine: RtcEngine? = null
    private var mReceiver: BroadcastReceiver? = null
    var mIntentFilter: IntentFilter?  = null
    var mIsRemote1Joined: Boolean = false
    var mIsRemote1Left: Boolean = false

    private val mRtcEventHandler = object : IRtcEngineEventHandler() {
        /**
         * Occurs when the first remote video frame is received and decoded.
         * This callback is triggered in either of the following scenarios:
         *
         *     The remote user joins the channel and sends the video stream.
         *     The remote user stops sending the video stream and re-sends it after 15 seconds. Possible reasons include:
         *         The remote user leaves channel.
         *         The remote user drops offline.
         *         The remote user calls the muteLocalVideoStream method.
         *         The remote user calls the disableVideo method.
         *
         * @param uid User ID of the remote user sending the video streams.
         * @param width Width (pixels) of the video stream.
         * @param height Height (pixels) of the video stream.
         * @param elapsed Time elapsed (ms) from the local user calling the joinChannel method until this callback is triggered.
         */
        override fun onFirstRemoteVideoDecoded(uid: Int,width: Int,height: Int,elapsed: Int) {
            runOnUiThread {
                if(!mIsRemote1Joined)
                    setupRemoteVideo(uid)
                else
                    setupRemoteVideo1(uid)
            }
        }

        override fun onUserOffline(uid: Int,reason: Int) {
            runOnUiThread {
                if(!mIsRemote1Left)
                    onRemoteUserLeft()
                else
                    onRemoteUserLeft1()
            }
        }

        override fun onUserMuteVideo(uid: Int,muted: Boolean) {
            runOnUiThread { onRemoteUserVideoMuted(uid,muted) }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.multiple_remoteview_layout)

        if (checkSelfPermission(Manifest.permission.RECORD_AUDIO,MultipleRemoteViewActivity.PERMISSION_REQ_ID_RECORD_AUDIO
            ) && checkSelfPermission(
                Manifest.permission.CAMERA,MultipleRemoteViewActivity.PERMISSION_REQ_ID_CAMERA
            )) {
            initAgoraEngineAndJoinChannel()
        }

    }

    private fun initAgoraEngineAndJoinChannel() {
        initializeAgoraEngine()

    }

    private fun checkSelfPermission(permission: String,requestCode: Int): Boolean {
        Log.i(MultipleRemoteViewActivity.LOG_TAG,"checkSelfPermission $permission $requestCode")
        if (ContextCompat.checkSelfPermission(
                this,permission
            ) != PackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(
                this,arrayOf(permission),requestCode
            )
            return false
        }
        return true
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,permissions: Array<String>,grantResults: IntArray
    ) {
        Log.i(MultipleRemoteViewActivity.LOG_TAG,"onRequestPermissionsResult " + grantResults[0] + " " + requestCode)

        when (requestCode) {
            MultipleRemoteViewActivity.PERMISSION_REQ_ID_RECORD_AUDIO -> {
                if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    checkSelfPermission(Manifest.permission.CAMERA,MultipleRemoteViewActivity.PERMISSION_REQ_ID_CAMERA
                    )
                } else {
                    showLongToast("No permission for " + Manifest.permission.RECORD_AUDIO)
                    finish()
                }
            }
            MultipleRemoteViewActivity.PERMISSION_REQ_ID_CAMERA -> {
                if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    initAgoraEngineAndJoinChannel()
                } else {
                    showLongToast("No permission for " + Manifest.permission.CAMERA)
                    finish()
                }
            }
        }
    }

    private fun showLongToast(msg: String) {
        this.runOnUiThread { Toast.makeText(applicationContext,msg,Toast.LENGTH_LONG).show() }
    }

    override fun onDestroy() {
        super.onDestroy()

        leaveChannel()
        /*
          Destroys the RtcEngine instance and releases all resources used by the Agora SDK.

          This method is useful for apps that occasionally make voice or video calls,to free up resources for other operations when not making calls.
         */
        RtcEngine.destroy()
        mRtcEngine = null
    }

    fun onLocalVideoMuteClicked(view: View) {
      /*  val iv = view as ImageView
        if (iv.isSelected) {
            iv.isSelected = false
            iv.clearColorFilter()
        } else {
            iv.isSelected = true
            iv.setColorFilter(resources.getColor(R.color.colorPrimary),PorterDuff.Mode.MULTIPLY)

        }

        // Stops/Resumes sending the local video stream.
        mRtcEngine!!.muteLocalVideoStream(iv.isSelected)*/

        val container = findViewById(R.id.local_video_view_container) as FrameLayout
        val surfaceView = container.getChildAt(0) as SurfaceView


      //  surfaceView.setZOrderMediaOverlay(!iv.isSelected) // surfaceView.visibility = if (iv.isSelected) View.GONE else View.VISIBLE
    }

/*    fun onLocalAudioMuteClicked(view: View) {
        val iv = view as ImageView
        if (iv.isSelected) {
            iv.isSelected = false
            iv.clearColorFilter()
        } else {
            iv.isSelected = true
            iv.setColorFilter(resources.getColor(R.color.colorPrimary),PorterDuff.Mode.MULTIPLY)
        }

        // Stops/Resumes sending the local audio stream.
        mRtcEngine!!.muteLocalAudioStream(iv.isSelected)
    }*/

/*
    fun onSwitchCameraClicked(view: View) {
        // Switches between front and rear cameras.
        mRtcEngine!!.switchCamera()
    }
*/

    fun onEndCallClicked(view: View) {
        finish()
    }

    private fun initializeAgoraEngine() {
        try {
            mRtcEngine = RtcEngine.create(
                baseContext,getString(R.string.agora_app_id),mRtcEventHandler
            )

            setupVideoProfile()
            setupLocalVideo()
            joinChannel()

        } catch (e: Exception) {
            Log.e(MultipleRemoteViewActivity.LOG_TAG,Log.getStackTraceString(e))

            throw RuntimeException(
                "NEED TO check rtc sdk init fatal error\n" + Log.getStackTraceString(e)
            )
        }
    }

    private fun setupVideoProfile() {
        // In simple use cases,we only need to enable video capturing
        // and rendering once at the initialization step.
        // Note: audio recording and playing is enabled by default.
        mRtcEngine!!.enableVideo()
//      mRtcEngine!!.setVideoProfile(Constants.VIDEO_PROFILE_360P,false) // Earlier than 2.3.0

        // Please go to this page for detailed explanation
        // https://docs.agora.io/en/Video/API%20Reference/java/classio_1_1agora_1_1rtc_1_1_rtc_engine.html#af5f4de754e2c1f493096641c5c5c1d8f
        mRtcEngine!!.setVideoEncoderConfiguration(
            VideoEncoderConfiguration(
                VideoEncoderConfiguration.VD_640x360,VideoEncoderConfiguration.FRAME_RATE.FRAME_RATE_FPS_15,VideoEncoderConfiguration.STANDARD_BITRATE,VideoEncoderConfiguration.ORIENTATION_MODE.ORIENTATION_MODE_FIXED_PORTRAIT
            )
        )
    }

    private fun setupLocalVideo() {

        val container = findViewById(R.id.local_video_view_container) as FrameLayout
        val surfaceView = RtcEngine.CreateRendererView(baseContext)
        surfaceView.setZOrderMediaOverlay(true)
        container.addView(surfaceView)
        // Initializes the local video view.
        // RENDER_MODE_FIT: Uniformly scale the video until one of its dimension fits the boundary. Areas that are not filled due to the disparity in the aspect ratio are filled with black.
        mRtcEngine!!.setupLocalVideo(VideoCanvas(surfaceView,VideoCanvas.RENDER_MODE_FIT,0))
    }

    private fun joinChannel() {
        // 1. Users can only see each other after they join the
        // same channel successfully using the same app id.
        // 2. One token is only valid for the channel name that
        // you use to generate this token.
        var token: String? = getString(R.string.agora_access_token)
        if (token!!.isEmpty()) {
            token = null
        }
        mRtcEngine!!.joinChannel(
            token,0
        ) // if you do not specify the uid,we will generate the uid for you

        var token1: String? = ("<token-string>")
        if (token1!!.isEmpty()) {
                token1 = null
        }
        mRtcEngine!!.joinChannel(
            token1,0
            ) // if you do not specify the uid,we will generate the uid for you
    }

    private fun setupRemoteVideo(uid: Int) {
        // Only one remote video view is available for this
        // tutorial. Here we check if there exists a surface
        // view tagged as this uid.
        val container = findViewById(R.id.remote_video_view_container) as FrameLayout

        if (container.childCount >= 1) {
            return
        }
        /*
          Creates the video renderer view.
          CreateRendererView returns the SurfaceView type. The operation and layout of the view
          are managed by the app,and the Agora SDK renders the view provided by the app.
          The video display view must be created using this method instead of directly
          calling SurfaceView.
         */
        val surfaceView = RtcEngine.CreateRendererView(baseContext)
        container.addView(surfaceView)
        // Initializes the video view of a remote user.
        mRtcEngine!!.setupRemoteVideo(VideoCanvas(surfaceView,uid))

        surfaceView.tag = uid // for mark purpose

        mIsRemote1Joined = true

      //  val tipMsg = findViewById<TextView>(R.id.quick_tips_when_use_agora_sdk) // optional UI
       // tipMsg.visibility = View.GONE
    }

    private fun setupRemoteVideo1(uid: Int) {
        // Only one remote video view is available for this
        // tutorial. Here we check if there exists a surface
        // view tagged as this uid.
        val container1 = findViewById(R.id.remote1_video_view_container) as FrameLayout

        if (container1.childCount >= 1) {
            return
        }

        /*
          Creates the video renderer view.
          CreateRendererView returns the SurfaceView type. The operation and layout of the view
          are managed by the app,and the Agora SDK renders the view provided by the app.
          The video display view must be created using this method instead of directly
          calling SurfaceView.
         */

        val surfaceView1 = RtcEngine.CreateRendererView(baseContext)
        container1.addView(surfaceView1)
        // Initializes the video view of a remote user.
        mRtcEngine!!.setupRemoteVideo(VideoCanvas(surfaceView1,uid))

        surfaceView1.tag = uid // for mark purpose

        //  val tipMsg = findViewById<TextView>(R.id.quick_tips_when_use_agora_sdk) // optional UI
        // tipMsg.visibility = View.GONE
    }

    private fun leaveChannel() {
        mRtcEngine!!.leaveChannel()
    }

    private fun onRemoteUserLeft() {
        val container = findViewById(R.id.remote_video_view_container) as FrameLayout
        container.removeAllViews()
        mIsRemote1Left = true
    }

    private fun onRemoteUserLeft1() {
        val container1 = findViewById(R.id.remote1_video_view_container) as FrameLayout
        container1.removeAllViews()
    }

    private fun onRemoteUserVideoMuted(uid: Int,muted: Boolean) {
        val container = findViewById(R.id.remote_video_view_container) as FrameLayout

        val surfaceView = container.getChildAt(0) as? SurfaceView

        val tag = surfaceView?.tag
        if (tag != null && tag as Int == uid) {
            surfaceView.visibility = if (muted) View.GONE else View.VISIBLE
        }

        val container1 = findViewById(R.id.remote1_video_view_container) as FrameLayout

        val surfaceView1 = container1.getChildAt(0) as? SurfaceView

        val tag1 = surfaceView1?.tag
        if (tag1 != null && tag1 as Int == uid) {
            surfaceView1.visibility = if (muted) View.GONE else View.VISIBLE
        }
    }

    companion object {

        private val LOG_TAG = MultipleRemoteViewActivity::class.java.simpleName

        private const val PERMISSION_REQ_ID_RECORD_AUDIO = 22
        private const val PERMISSION_REQ_ID_CAMERA = PERMISSION_REQ_ID_RECORD_AUDIO + 1
    }
}

现在我的代码问题是:我在三个设备上以相同的应用程序ID加入同一频道,一个是Web chrome应用程序,另外两个在android设备上。当我从两台设备加入时,我可以看到一个远程视图和一个本地视图,但是当这三个设备已加入同一频道时,如果其中一台设备离开了频道,则这两个远程视图都将停止工作并且无法加入同一频道再次。

请提出解决方案...

解决方法

您可以查看我们的小组视频示例应用程序以供参考:https://github.com/AgoraIO/Basic-Video-Call/tree/master/Group-Video/OpenVideoCall-Android

通常,如果要让多个人加入同一频道,则需要确保他们具有相同的应用ID和频道名称。

关于令牌,要加入频道的每个用户都需要有单独的UID,这也意味着他们的令牌会有所不同。

因此工作流程将如下所示:

用户A要加入通道->用户A向后端发送请求->服务器生成一个随机UID并使用该令牌生成新令牌->服务器返回生成的UID和令牌->用户A使用这些凭据来加入频道

加入该频道的每个后续用户都将使用相同的工作流程。 请记住,对于此工作流程,UID是由您自己生成的,而不是由Agora随机生成的(即,您不应像完成操作那样将0作为UID传递)。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res