Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Пример Android-приложения для видеоконференции

Данный пример может использоваться для участия в видеоконференции для трех пользователей на Web Call Server и позволяет публиковать WebRTC-поток.

...

Ниже расположены контролы для отключения/включения аудио и видео для публикуемого потока, поле ввода текстового сообщения и лог сообщений.

Работа с кодом примера

Для разбора кода возьмем класс ConferenceActivity.java примера conference, который доступен для скачивания в соответствующей сборке 1.0.1.38.

...

Code Block
languagejs
themeRDark
@Override
public void onState(final Room room) {
    /**
      * After joining, Room object with data of the room is received.
      * Method Room.getParticipants() is used to check the number of already connected participants.
      * The method returns collection of Participant objects.
      * The collection size is determined, and, if the maximum allowed number (in this case, three) has already been reached, the user leaves the room with method Room.leave().
      */
    if (room.getParticipants().size() >= 3) {
        room.leave(null);
        runOnUiThread(
             new Runnable() {
                 @Override
                 public void run() {
                     mJoinStatus.setText("Room is full");
                     mJoinButton.setEnabled(true);
                 }
             }
        );
        return;
    }


    final StringBuffer chatState = new StringBuffer("participants: ");

    /**
      * Iterating through the collection of the other participants returned by method Room.getParticipants().
      * There is corresponding Participant object for each participant.
      */
    for (final Participant participant : room.getParticipants()) {
        /**
          * A player view is assigned to each of the other participants in the room.
          */
        final ParticipantView participantView = freeViews.poll();
        if (participantView != null) {
            chatState.append(participant.getName()).append(",");
            busyViews.put(participant.getName(), participantView);

            /**
              * Playback of the stream being published by the other participant is started with method Participant.play().
              * SurfaceViewRenderer to be used to display the video stream is passed when the method is called.
              */
            participant.play(participantView.surfaceViewRenderer);
            runOnUiThread(...
                 new Runnable() {}
                     @Override}
                     public void run() {
                         participantView.login.setText(participant.getName());
                     }
                 }
            );
        }
    }
    runOnUiThread(
        new Runnable() {
            @Override
            public void run() {
                mJoinButton.setText(R.string.action_leave);
                mJoinButton.setTag(R.string.action_leave);
                mJoinButton.setEnabled(true);
                mJoinStatus.setText("");
                mPublishButton.setEnabled(true);
                mSendButton.setEnabled(true);
                if (room.getParticipants().size() == 0) {
                    addMessageHistory("chat", "room is empty");
                } else {
                    addMessageHistory("chat", chatState.substring(0, chatState.length() - 1));
                }
            }
        }
    );
}

6. Публикация видеопотока.

Room.publish() код

Методу передаются:

  • SurfaceViewRenderer, который будет использоваться для отображения видео с камеры
  • параметр record, определяющий, будет ли записываться публикуемый поток
Code Block
languagejs
themeRDark
case PUBLISH_REQUEST_CODE: {
    if (grantResults.length == 0 ||
           grantResults[0] != PackageManager.PERMISSION_GRANTED ||
           grantResults[1] != PackageManager.PERMISSION_GRANTED) {

        Log.i(TAG, "Permission has been denied by user");
    } else {
        mPublishButton.setEnabled(false);
        /**
          * Stream is created and published with method Room.publish().
          * SurfaceViewRenderer to be used to display video from the camera is passed to the method.
          */
        boolean record = mRecord.isChecked();
        StreamOptions streamOptions = new StreamOptions();
        streamOptions.setRecord(record);
        stream = room.publish(localRenderer, streamOptions);

        /**
          * Callback function for stream status change is added to make appropriate changes in controls of the interface when stream is being published.
          */
        stream.on(new StreamStatusEvent() {
            @Override
            public void onStreamStatus(final Stream stream, final StreamStatus streamStatus) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (StreamStatus.PUBLISHING.equals(streamStatus)) {
                            mPublishButton.setText(R.string.action_stop);
                            mPublishButton.setTag(R.string.action_stop);
                            mMuteAudio.setEnabled(true);
                            mMuteVideo.setEnabled(true);
                        } else {
                            mPublishButton.setText(R.string.action_publish);
                            mPublishButton.setTag(R.string.action_publish);
                            mMuteAudio.setEnabled(false);
                            mMuteAudio.setChecked(false);
                            mMuteVideo.setEnabled(false);
                            mMuteVideo.setChecked(false);
                            ConferenceActivity.this.stream = null;
                        }
                        if (mJoinButton.getTag() == null || Integer.valueOf(R.string.action_join).equals(mJoinButton.getTag())) {...
}


6. Публикация видеопотока.

Room.publish() код

Методу передаются:

  • SurfaceViewRenderer, который будет использоваться для отображения видео с камеры
  • параметр record, определяющий, будет ли записываться публикуемый поток
Code Block
languagejs
themeRDark
case PUBLISH_REQUEST_CODE: {
    if (grantResults.length == 0 ||
           grantResults[0] != PackageManager.PERMISSION_GRANTED ||
           grantResults[1] !=  mPublishButton.setEnabled(false);PackageManager.PERMISSION_GRANTED) {

        Log.i(TAG, "Permission has been denied by user");
    } else {
    } else {
  mPublishButton.setEnabled(false);
        /**
          * Stream is created and published with method mPublishButtonRoom.setEnabledpublish(true);.
          * SurfaceViewRenderer to be used to display video from the camera   is }
passed to the method.
          */
        boolean record = mPublishStatusmRecord.setTextisChecked(streamStatus.toString());
        StreamOptions streamOptions =          }new StreamOptions();
                }streamOptions.setRecord(record);
        stream =   }room.publish(localRenderer, streamOptions);
        });...
        Log.i(TAG, "Permission has been granted by user");
    }
}

...