メニュー

Expand
ページを評価:

Getting Started: Android

Twilio is launching a new Console. Some screenshots on this page may show the Legacy Console and therefore may no longer be accurate. We are working to update all screenshots to reflect the new Console experience. Learn more about the new Console.

目次

This guide provides you with an overview of the key objects you'll use in the Programmable Video API to build your video application with the Twilio Programmable Video Android SDK.

Note: If you haven’t already done so, take a look at the open source video collaboration app and quickstart apps. Then come back to this guide for more detail on how to add video to your own app.

WebRTCをお使いいただいた経験があるなら、Programmable Videoは完成度の高いオーディオおよびビデオアプリケーションの構築を容易にするために、WebRTCの下位レベルAPIの単純なラッパーを提供していることに気づかれるでしょう。 依然としてより下位レベルのプリミティブにアクセスできますが、入門には必要ありません。

加えて、Programmable VideoはWebRTCを使用して洗練されたアプリケーションを構築するために必要な不足したピース: グローバルSTUN/TURNリレー、大規模な電話会議および録音用のメディアサービス、そしてシグナリングのためのインフラが全て含まれています。

Video API概要

まずは、Programmable Video APIの概要からはじめましょう:

  • Roomはリアルタイムのオーディオ、ビデオ、そして画面共有セッションを表し、これはProgrammable Videoアプリケーションにおける基本となる構成要素になります。
  • In a Peer-to-peer Room, media flows directly between participants. Supports up to 10 participants in a mesh topology.
  • In a Group Room, media is routed through Twilio's Media Servers. Supports up to 50 participants.
  • Participants は、Roomに接続され、他のクライアントとオーディオまたは(および)ビデオのメディアと共有しているクライアントアプリケーションを表します。
  • Tracks は、Roomと共有されているオーディオとビデオのストリームを表します。
  • LocalTracks represent the audio and video captured from the local microphone and camera.
  • RemoteTracks represent the audio and video tracks from other participants connected to the Room.

下記のコード例はルームとその参加者に関連して開発者たるあなたが行うべき共通のタスクを示しています。

前提条件

To start using the Android Programmable Video SDK in your apps, you need to perform a few basic tasks first.

1. Get the Programmable Video Android SDK

The Android Video SDK is distributed through Maven Central.

To install the Android Video SDK, ensure the following configuration is in your build.gradle file:

Maven Central

Gradle

Add the following lines to your build.gradle file.

allprojects {
    repositories {
        mavenCentral()
    }
}

// The Video library resides on Maven Central
implementation 'com.twilio:video-android:7.0.0'

android {
    compileOptions {
        sourceCompatibility 1.8
        targetCompatibility 1.8
    }
}
Proguard

Add the following lines to your proguard-project.txt file.

-keep class tvi.webrtc.** { *; }
-keep class com.twilio.video.** { *; }
-keepattributes InnerClasses
サポートされるデバイス

The Android SDK supports Android API level 21 and higher. It is built for armeabi-v7a, arm64-v8a, x86, and x86_64 architectures.

2. Get an API Key

APIキーはTwilioAPIにアクセスするためのクレデンシャルを表します。2つの理由があります。

For the purposes of this guide, we will create our API Key from the Twilio Console.

  • Go to the API Keys section under Tools in the Twilio Console.
  • Click on “Create a New API Key”, add a friendly name and save your Key and Secret.

3. Generate an Access Token

To execute the code samples below, you'll need to generate an Access Token. An Access Token is a short-lived credential used to authenticate your client-side application to Twilio.

You can generate an Access Token using either the Twilio CLI or a Twilio helper library. For application testing purposes, the Twilio CLI provides a quick way to generate Access Tokens that you can then copy/paste into your application.

To use the CLI, you will need to install the Twilio CLI and log in to your Twilio account from the command line; see the CLI Quickstart for instructions. Then, you can install the Token CLI plugin with the following command:

twilio plugins:install @twilio-labs/plugin-token

To generate an Access Token, run the following command. --identity is a required argument and should be a string that represents the user identity for this Access Token.

twilio token:video --identity=<identity>

In a production application, your back-end server will need to generate an Access Token for every user in your application. Visit the User Identity and Access Token guide to learn more. You can find examples of how to generate an Access Token for a participant using Twilio's helper libraries in the User Identity and Acces Token guide.

ルームに接続する

Call Video.connect() to connect to a Room from your Android application. Once connected, you can send and receive audio and video streams with other Participants who are connected to the Room.

private Room.Listener roomListener() {
  return new Room.Listener() {
      @Override
      public void onConnected(Room room) {
        Log.d(TAG,"Connected to " + room.getName());
      }
  }
}

public void connectToRoom(String roomName) {
  ConnectOptions connectOptions = new ConnectOptions.Builder(accessToken)
    .roomName(roomName)
    .audioTracks(localAudioTracks)
    .videoTracks(localVideoTracks)
    .dataTracks(localDataTracks)
    .build();
  room = Video.connect(context, connectOptions, roomListener);
}

Roomへの接続時には、アクセストークンを渡すことが必要です。 またオプションで、下記を渡すこともできます:

  • ルーム名: 参加したいルームの名前を動的に指定できます。 (メモ: ルーム名をアクセストークンにエンコードできます。 こうすることでユーザーはトークンで指定されたRoomにのみ接続できます。)
  • Local audio, video, or data tracks, to begin sharing pre-created local media with other Participants in the Room upon connecting.

Roomの名前には、参加したいRoomを指定します。 その名前のRoomがまだ存在していない場合、接続に先立って作成されます。 ルームがすでにアクティブな場合はルームに接続され、同じルームに接続されている他の参加者からの通知を受信します。 ルーム名はアカウント内で一意でなければなりません。

また、Rooms REST APIを使用してRoomに接続することも可能です。 さらなる詳細については、REST API Roomsリソースを参照してください。

Example: Create a Room called DailyStandup

 curl -XPOST 'https://video.twilio.com/v1/Rooms' \
 -u '{API Key SID}:{API Secret}' \
 -d 'UniqueName=DailyStandup'

注 : Type属性を指定しない場合、Twilioは既定でGroupルームを作成します。

既定のRoom設定

You can also set the room type from the Room Settings page in the Twilio Video Console. Twilio will use the room type set on Room Settings page, when you create a room from the client-side or the REST API.

メモ: Twilioは、Room設定ページの既定としてRoomタイプをGroupに設定します。

StatusCallback URLが設定されている場合、Roomが作成されると、Twilioはroom-created Webhookイベントを呼び出します。 クライアント側からRoomを作成したい場合、Room設定ページからStatusCallback URLを設定できます。 REST APIでRoomを作成する場合、Room作成時にStatusCallback URLを指定することが必要です。

 curl -XPOST 'https://video.twilio.com/v1/Rooms' \
 -u '{API Key SID}:{API Secret}' \
 -d 'UniqueName=DailyStandup' \
 -d 'StatusCallback=https://hooks.yoursite.com/room-events' \
 -d 'StatusCallbackMethod=POST' \
 -d 'Type=group'

Enabling Room Recordings

Recordings can be enabled only on Group Rooms. Set Recordings to Enabled to record participants when they connect to a Group Room. Recordings can also be enabled on Group Rooms through via the Rest API at Room creation time by setting the RecordParticipantsOnConnect property to true.

curl -XPOST 'https://video.twilio.com/v1/Rooms' \
-u 'SKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX:your_api_key_secret' \
-d 'UniqueName=DailyStandup' \
-d 'Type=group' \
-d 'RecordParticipantsOnConnect=true' \
-d 'StatusCallback=http://example.org'

ルームに参加する

If you'd like to join a Room you know already exists, you handle that exactly the same way as creating a room: just pass the Room name to the connect method. Once in a Room, you'll receive a participantConnectedevent for each Participant that successfully joins. Querying the participants getter will return any existing Participants who have already joined the Room.

private Room.Listener roomListener() {
  return new Room.Listener() {
    @Override
    public void onConnected(Room room) {
      Log.d(TAG,"Connected to " + room.getName());
    }
  }
}

public void connectToRoom(String roomName) {
  ConnectOptions connectOptions = new ConnectOptions.Builder(accessToken)
    .roomName(roomName)
    .audioTracks(localAudioTracks)
    .videoTracks(localVideoTracks)
    .dataTracks(localDataTracks)
    .build();
  room = Video.connect(context, connectOptions, roomListener);
}

Set up local media

下記の方法で、いろいろなプラットフォーム上のデバイスのマイク、カメラ、あるいは画面共有からローカルメディアを取り込むことができます:

Androidアプリケーションでは、LocalAudioTrackを作成することでオーディオデータの取り込みを開始し、関連づけられたVideoCapturerLocalVideoTrackを追加します。 Android Video SDKはカメラおよび画面共有の双方について対して、カスタマイズ可能なビデオ取り込みを提供します。

// Create an audio track
boolean enable = true;
LocalAudioTrack localAudioTrack = LocalAudioTrack.create(context, enable);

// A video track requires an implementation of a VideoCapturer. Here's how to use the front camera with a Camera2Capturer.
Camera2Enumerator camera2Enumerator = new Camera2Enumerator(context);
String frontCameraId = null;
for (String cameraId : camera2Enumerator.getDeviceNames()) {
    if (camera2Enumerator.isFrontFacing(cameraId)) {
        frontCameraId = cameraId;
        break;
    }
}
if(frontCameraId != null) {
    // Create the CameraCapturer with the front camera 
    CameraCapturer cameraCapturer = new Camera2Capturer(context, frontCameraId);

    // Create a video track
    LocalVideoTrack localVideoTrack = LocalVideoTrack.create(context, enable, cameraCapturer);

    // Rendering a local video track requires an implementation of VideoSink
    // Let's assume we have added a VideoView in our view hierarchy
    VideoView videoView = (VideoView) findViewById(R.id.video_view);

    // Render a local video track to preview your camera
    localVideoTrack.addSink(videoView);

    // Release the audio track to free native memory resources
    localAudioTrack.release();

    // Release the video track to free native memory resources
    localVideoTrack.release();
}

Connect as a publish-only Participant

For some use cases you may wish to connect as a publish-only Participant that is not subscribed to any Tracks. If you are connecting to a Group Room, you may disable automatic subscription behavior via ConnectOptions.

public void connectToRoom(String roomName) {
  ConnectOptions connectOptions = new ConnectOptions.Builder(accessToken)
    .roomName("my-room")
    .enableAutomaticSubscription(false)
    .build();
  room = Video.connect(context, connectOptions, roomListener);
}

リモート参加者を扱う

接続済みの参加者を処理する

ルームへの接続時には、すでに他の参加者がいる可能性があります。 connected イベント・コールバック内で participants getterを使用すれば、すでに存在する参加者を確認できます。

// Connect to room
Room room = Video.connect(context, connectOptions, new Room.Listener() {
    @Override
    public void onConnected(Room room) {}

    @Override
    public void onConnectFailure(Room room, TwilioException e) {}

    @Override
    public void onDisconnected(Room room, TwilioException e) {}

    @Override
    public void onRecordingStarted(Room room) {}

    @Override
    public void onRecordingStopped(Room room) {}

    @Override
    public void onParticipantConnected(Room room, RemoteParticipant participant) {
        Log.i("Room.Listener", participant.getIdentity() + " has joined the room.");
    }

    @Override
    public void onParticipantDisconnected(Room room, RemoteParticipant participant) {
        Log.i("Room.Listener", participant.getIdentity() + " has left the room.");
    }
);

// ... Assume we have received the connected callback

// After receiving the connected callback the LocalParticipant becomes available
LocalParticipant localParticipant = room.getLocalParticipant();
Log.i("LocalParticipant ", localParticipant.getIdentity());

// Get the first participant from the room
RemoteParticipant participant = room.getRemoteParticipants().get(0);
Log.i("HandleParticipants", participant.getIdentity() + " is in the room.");

参加者接続イベントを処理する

When Participants connect to or disconnect from a Room that you're connected to, you'll be notified via an event listener: Similar to Room Events, Twilio will fire Participant events if the StatusCallback webhook URL is set when the Room is created. These events help your application keep track of the participants who join or leave a Room.

private Room.Listener roomListener() {
  return new Room.Listener() {

    @Override
    public void onParticipantConnected(Room room, RemoteParticipant participant) {
      Log.v(TAG, "Participant connected: " + participant.getIdentity());
    }

    @Override
    public void onParticipantDisconnected(Room room, RemoteParticipant participant) {
      Log.v(TAG, "Participant disconnected: " + participant.getIdentity());
    }
  };
}

リモート参加者のビデオを表示する

リモートの参加者によって送信されたビデオ・トラックを見えるようにするには、それを画面にレンダリングする必要があります。

// First, we set a Media Listener when a Participant first connects:
private Room.Listener roomListener() {
  return new Room.Listener() {
    @Override
    public void onParticipantConnected(Room room, RemoteParticipant participant) {
      participant.setListener(remoteParticipantListener());
    }
  };
}

/* In the Participant listener, we can respond when the Participant adds a Video
Track by rendering it on screen: */
private RemoteParticipant.Listener remoteParticipantListener() {
  return new RemoteParticipant.Listener() {
      @Override
      public void onVideoTrackSubscribed(RemoteParticipant participant,
                                         RemoteVideoTrackPublication remoteVideoTrackPublication,
                                         RemoteVideoTrack remoteVideoTrack) {
        primaryVideoView.setMirror(false);
        remoteVideoTrack.addSink(primaryVideoView);
      }
  };
}

ルームへの参加

カメラプレビューを表示する

ルームへの入室前に、ご自身のカメラ映りを確かめたいことがあるでしょう。 おまかせを! 各SDKでは、アクティブなルームのコンテキストの外側でルーカルのカメラ・プレビューをレンダリングする方法をご用意しています。

/* The CameraCapturer is a default video capturer provided by Twilio which can
   capture video from the front or rear-facing device camera */
private CameraCapturer cameraCapturer;

/* A VideoView receives frames from a local or remote video track and renders them
   to an associated view. */
private VideoView primaryVideoView;

// Start the camera preview
LocalVideoTrack localVideoTrack = LocalVideoTrack.create(context, true, cameraCapturer);
primaryVideoView.setMirror(true);
localVideoTrack.addSink(primaryVideoView);

// Release the local video track to free native memory resources once you are done
localVideoTrack.release();

Note: See this snippet to see how to initialize a CameraCapturer.

ルームから切断する

現在参加しているルームから切断できます。 他の参加者は participantDisconnected イベントを受信します。

// To disconnect from a Room, we call:
room.disconnect();

// This results in a call to Room.Listener#onDisconnected
private Room.Listener roomListener() {
  return new Room.Listener() {
    @Override
    public void onDisconnected(Room room, TwilioException e) {
        Log.d(TAG,"Disconnected from " + room.getName());
    }
  };
}

Room reconnection

The Video SDK will raise notifications when a Room is reconnecting due to a network disruption. A Room reconnection is triggered due to a signaling or media reconnection event.

private Room.Listener roomListener() {
  return new Room.Listener() {

    /*
     * Exception will be either TwilioException.SIGNALING_CONNECTION_DISCONNECTED_EXCEPTION or
     * TwilioException.MEDIA_CONNECTION_ERROR_EXCEPTION
     */
    @Override
    public void onReconnecting(Room room, TwilioException exception) {
      Log.v(TAG, "Reconnecting to room: " + room.getName() + ", exception = " + exception.getMessage());
    }

    @Override
    public void onReconnected(Room room) {
      Log.v(TAG, "Reconnected to room " + room.getName());
    }
  };
}

Reconnections in a Peer-to-Peer Room

In a Peer-to-Peer Room, each Participant has media connections to all the other Participants in the Room. If all media connections between the LocalParticipant and all other Participants are broken, then the LocalParticipant's Room will enter the reconnecting state until media connectivity with at least one Participant is re-established.

Server-side control

The Programmable Video REST API allows you to control your video applications from your back-end server via HTTP requests. To learn more check out the Programmable Video REST API docs.

ヘルプ

We love feedback and questions especially those with helpful debugging information so we can diagnose and respond quickly. When submitting issues or support tickets, it would be great if you add the following:

  • Description - A description of the issue
  • Steps to reproduce - List the steps necessary to reproduce the issue
  • Code - Include any applicable code snippets that would assist in reproduction and troubleshooting
  • Expected Behavior - What you expect to happen
  • Actual Behavior - What actually happens
  • Reproduces How Often - What percentage of the time does it reproduce?
  • Logs - Any log output when the issue occurs. See below for enabling debug level logging.
  • Video Android SDK - The version(s) of the Video Android SDK where this issue is apparent
  • Android Version - The version(s) of Android where this issue is apparent
  • Android Device - The Android device(s) where this issue is apparent
  • Room SID - Room SIDs can be useful for tracing backend issues

After gathering the above information, you can get help in a few ways:

Enabling Debug Logging

To enable debug level logging, add the following code in your application:

/*
 * Set the log level of the Video Android SDK
 */
Video.setLogLevel(LogLevel.DEBUG);

/*
 * If your application is experiencing an issue related to a specific
 * module, you can set the log level of each of the following modules.
 */
Video.setModuleLogLevel(LogModule.CORE, LogLevel.DEBUG);
Video.setModuleLogLevel(LogModule.PLATFORM, LogLevel.DEBUG);
Video.setModuleLogLevel(LogModule.SIGNALING, LogLevel.DEBUG);
Video.setModuleLogLevel(LogModule.WEBRTC, LogLevel.DEBUG);
ページを評価:

ヘルプが必要ですか?

We all do sometimes; code is hard. Get help now from our support team, or lean on the wisdom of the crowd by visiting Twilio's Community Forums or browsing the Twilio tag on Stack Overflow.

        
        
        

        フィードバックくださりありがとうございます!

        We are always striving to improve our documentation quality, and your feedback is valuable to us. How could this documentation serve you better?

        Sending your feedback...
        🎉 Thank you for your feedback!
        Something went wrong. Please try again.

        Thanks for your feedback!

        Refer us and get $10 in 3 simple steps!

        ステップ1

        Get link

        Get a free personal referral link here

        ステップ2:

        Give $10

        Your user signs up and upgrade using link

        ステップ3

        Get $10

        1,250 free SMSes
        OR 1,000 free voice mins
        OR 12,000 chats
        OR more