你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

快速入门:创建和管理房间资源

本快速入门帮助你开始使用 Azure 通信服务的房间资源。 room 是服务器管理的通信空间,供一组已知的固定参与者在预定的持续时间内进行协作。 房间概念文档介绍了 rooms 的更多详细信息和用例。

对象模型

下表列出了 room 对象的主要属性:

名称 说明
roomId 唯一的 room 标识符。
validFrom 可以使用 room 的最早时间。
validUntil 可以使用 room 的最晚时间。
pstnDialOutEnabled 在会议室中启用或禁用拨出到 PSTN 号码。
participants room 的参与者列表。 指定为 CommunicationIdentifier
roleType 房间参与者的角色。 可以为 PresenterAttendeeConsumer

先决条件

设置

添加扩展

使用 az extension 命令为 Azure CLI 添加 Azure 通信服务扩展。

az extension add --name communication

登录 Azure CLI

你需要登录到 Azure CLI。 可以通过从终端运行 az login 命令并提供凭据进行登录。

将连接字符串存储在环境变量中

可通过配置 AZURE_COMMUNICATION_CONNECTION_STRING 环境变量以使用 Azure CLI 密钥操作,而无需使用 --connection_string 来传入连接字符串。 若要配置环境变量,请打开控制台窗口,然后从以下选项卡中选择操作系统。 将 <connectionString> 替换为实际的连接字符串。

setx AZURE_COMMUNICATION_CONNECTION_STRING "<connectionString>"

添加环境变量后,你可能需要重启任何需要读取环境变量的正在运行的程序(包括控制台窗口)。 例如,如果使用 Visual Studio 作为编辑器,请在运行示例之前重启 Visual Studio。

Operations

创建房间

使用 rooms create 命令创建会议室。

az communication rooms create --presenter-participants "<participantId>" --consumer-participants "<participantId>" --attendee-participant "<participantId>" --valid-from "<valid-from>" --valid-until "<valid-until>" --pstn-dial-out-enabled "<pstn-dial-out-enabled>" --connection-string "<connection-string>"
  • 可选择使用 <participantId> 将参与者的类型指定为演示参与者、使用参与者或与会参与者。 如果未指定值,则默认值为空。
  • <connection-string> 替换为你的 Azure 通信服务连接字符串。
  • 可选择使用 <valid-from> 以 ISO8601 格式指定会议室开放加入时的时间戳,例如:2022-07-14T10:21。
  • 可选择使用 <valid-until> 以 ISO8601 格式指定会议室关闭加入时的时间戳,例如:2022-07-14T10:21。
  • 通过设置此标志(“True”或“False”)使用 <pstn-dial-out-enabled>(可选),以启用或禁用会议室的 PSTN 拨出。 默认情况下,创建聊天室时,此标志设置为“False”。

如果已如上所述将连接字符串存储在环境变量中,则无需将其传递给命令。

az communication rooms create 

为会议室启用 PSTN 拨出功能

通过将 --pstn-dial-out-enabled 参数定义为“True”,可以在 rooms create 期间启用 PSTN 拨出。 还可以通过指定 --pstn-dial-out-enabled 参数在 rooms update 期间修改此功能。

az communication rooms create --pstn-dial-out-enabled "<pstn-dial-out-enabled>" --connection-string "<connection-string>"
az communication rooms update --pstn-dial-out-enabled "<pstn-dial-out-enabled>" --room "<roomId>"
  • 若要启用或禁用会议室的 PSTN 拨出,请设置 <pstn-dial-out-enabled> 标志(“True”或“False”)。

获取会议室

rooms get 命令返回现有会议室的特性。

az communication rooms get --room "<roomId>" 
  • <roomId> 替换为会议室 ID。

更新会议室的时间范围

可以更新会议室的时间戳。 在调用 room update 命令之前,请确保已获取具有有效时间范围的新会议室。

az communication rooms update --valid-from "<valid-from>" --valid-until "<valid-until>" --pstn-dial-out-enabled "<pstn-dial-out-enabled>" --room "<roomId>"
  • <valid-from> 替换为 ISO8601 格式的时间戳,例如:2022-07-14T10:21,以指定会议室何时开放供加入。 应与 --valid-until 一起使用。
  • <valid-until> 替换为 ISO8601 格式的时间戳,例如:2022-07-14T10:21,以指定何时无法再加入会议室。 应与 --valid-from 一起使用。
  • 替换 <pstn-dial-out-enabled> 设置此标志(“True”或“False”),以启用或禁用会议室的 PSTN 拨出。 应与 --pstn-dial-out-enabled 一起使用。
  • <roomId> 替换为会议室 ID。

列出所有活动会议室

rooms list 命令会返回属于你的 Azure 通信服务资源的所有活动会议室。

az communication rooms list

添加新参与者或更新现有参与者

创建会议室时,可以通过添加新参与者或更新其中的现有参与者来更新该会议室。 在调用 room participant add-or-update 命令之前,请确保已获取新用户。

使用 identity user create 命令创建一个由 participantId 标识的新参与者。

az communication identity user create

将用户作为参与者添加到会议室。

az communication rooms participant add-or-update --attendee-participant "<participantId>" --room "<roomId>"
  • <participantId> 替换为参与者 ID。 如果会议室中不存在 <participantId>,则该参与者将作为与会者角色添加到会议室。 否则,参与者的角色将更新为与会者角色。
  • <roomId> 替换为会议室 ID。

获取会议室中的参与者列表

az communication rooms participant get --room "<roomId>"
  • <roomId> 替换为会议室 ID。

从会议室中移除参与者

可以使用 rooms participant -remove 从会议室中移除会议室参与者。

az communication rooms participant remove --room "<roomId>" --participants "<participant1>" "<participant2>" "<participant3>"
  • <roomId> 替换为会议室 ID。
  • <participant1><participant2><participant3> 替换为之前通过运行 identity user create 命令获取的用户 ID。

删除房间

与创建会议室类似,也可以删除会议室。

使用 room delete 命令删除现有会议室。

az communication rooms delete --room "<roomId>"
  • <roomId> 替换为会议室 ID。

本快速入门帮助你开始使用 Azure 通信服务的房间资源。 room 是服务器管理的通信空间,供一组已知的固定参与者在预定的持续时间内进行协作。 房间概念文档介绍了 rooms 的更多详细信息和用例。

先决条件

代码示例

可以在 GitHub 上查看并下载本快速入门的示例代码。

设置

新建 C# 应用程序

在控制台窗口(例如 cmd、PowerShell 或 Bash)中,使用 dotnet new 命令创建名为 RoomsQuickstart 的新控制台应用。 此命令将创建包含单个源文件的简单“Hello World”C# 项目:Program.cs

dotnet new console -o RoomsQuickstart

将目录更改为新创建的应用文件夹,并使用 dotnet build 命令编译应用程序。

cd RoomsQuickstart
dotnet build

安装包

使用 [NuGet][https://www.nuget.org/] 安装适用于 .NET 的 Azure 通信房间客户端库:

dotnet add package Azure.Communication.Rooms

需要使用适用于 .NET 版本 1.1.0 或更高版本的 Azure 通信室客户端库。

设置应用框架

Program.cs 文件中,添加以下代码以导入所需的命名空间并创建基本程序结构。


using System;
using Azure;
using Azure.Core;
using Azure.Communication.Rooms;

namespace RoomsQuickstart
{
    class Program
    {
        static async System.Threading.Tasks.Task Main(string[] args)
        {
            Console.WriteLine("Azure Communication Services - Rooms Quickstart");

            // Quickstart code goes here
        }
    }
}

初始化房间客户端

创建一个新的 RoomsClient 对象,用于创建新的 rooms 并管理其属性和生命周期。 Communications Service 的连接字符串将用于对请求进行身份验证。 有关连接字符串的详细信息,请参阅此页


// Find your Communication Services resource in the Azure portal
var connectionString = "<connection_string>";
RoomsClient roomsClient = new RoomsClient(connectionString);

创建房间

设置会议室参与者

若要设置谁可以加入会议室,你需要拥有这些用户的标识列表。 可以按照此处的说明创建用户和颁发访问令牌。 或者,如果要按需创建用户,可以使用 CommunicationIdentityClient 进行创建。

要使用 CommunicationIdentityClient,请安装以下包:

dotnet add package Azure.Communication.Identity

此外,在 Program.cs 文件顶部导入包的命名空间:

using Azure.Communication.Identity;

现在,CommunicationIdentityClient 可以初始化并用于创建用户:

// Create identities for users who will join the room
CommunicationIdentityClient identityClient = new CommunicationIdentityClient(connectionString);
CommunicationUserIdentifier user1 = identityClient.CreateUser();
CommunicationUserIdentifier user2 = identityClient.CreateUser();

然后,通过引用这些用户来创建会议室参与者的列表:

List<RoomParticipant> participants = new List<RoomParticipant>()
{
    new RoomParticipant(user1) { Role = ParticipantRole.Presenter },
    new RoomParticipant(user2) // The default participant role is ParticipantRole.Attendee
};

初始化会议室

使用在上述代码片段中定义的 participants 创建新的 room

// Create a room
DateTimeOffset validFrom = DateTimeOffset.UtcNow;
DateTimeOffset validUntil = validFrom.AddDays(1);
CancellationToken cancellationToken = new CancellationTokenSource().Token;

CommunicationRoom createdRoom = await roomsClient.CreateRoomAsync(validFrom, validUntil, participants, cancellationToken);

// CreateRoom or CreateRoomAsync methods can take CreateRoomOptions type as an input parameter.
bool pstnDialOutEnabled = false;
CreateRoomOptions createRoomOptions = new CreateRoomOptions()
{
    ValidFrom = validFrom,
    ValidUntil = validUntil,
    PstnDialOutEnabled = pstnDialOutEnabled,
    Participants = participants
};

createdRoom = await roomsClient.CreateRoomAsync(createRoomOptions, cancellationToken);
string roomId = createdRoom.Id;
Console.WriteLine("\nCreated room with id: " + roomId);

由于 rooms 是服务器端实体,因此你可能想要跟踪 roomId 并将其持久保存在所选的存储媒体中。 可以引用 roomId 来查看或更新 room 对象的属性。

为会议室启用 PSTN 拨出功能

默认情况下,每个 room 都禁用了 PSTN 拨出功能。 在创建时,通过将 pstnDialOutEnabled 参数定义为 true,可以为 room 启用 PSTN 拨出。 还可以通过为 pstnDialOutEnabled 参数发出更新请求来为 room 修改此功能。

// Create a room
CancellationToken cancellationToken = new CancellationTokenSource().Token;

// CreateRoom or CreateRoomAsync methods to create a room with PSTN dial out capability
bool pstnDialOutEnabled = true;
CreateRoomOptions createRoomOptions = new CreateRoomOptions()
{
    PstnDialOutEnabled = pstnDialOutEnabled,
};

CommunicationRoom createdRoom = await roomsClient.CreateRoomAsync(createRoomOptions, cancellationToken);
Console.WriteLine("\nCreated a room with PSTN dial out enabled: " + createdRoom.PstnDialOutEnabled);

// UpdateRoom or UpdateRoomAsync methods can take UpdateRoomOptions to enable or disable PSTN dial out capability
pstnDialOutEnabled = false;
UpdateRoomOptions updateRoomOptions = new UpdateRoomOptions()
{
    PstnDialOutEnabled = pstnDialOutEnabled,
};

CommunicationRoom updatedRoom = await roomsClient.UpdateRoomAsync(roomId, updateRoomOptions, cancellationToken);
Console.WriteLine("\nUpdated a room with PSTN dial out enabled: " + updatedRoom.PstnDialOutEnabled);

获取现有房间的属性

通过引用 roomId 来检索现有 room 的详细信息:


// Retrieve the room with corresponding ID
CommunicationRoom room = await roomsClient.GetRoomAsync(roomId);
Console.WriteLine("\nRetrieved room with id: " + room.Id);

更新房间的生存期

可以通过对 ValidFromValidUntil 参数发出更新请求来修改 room 的生存期。 一个房间的有效期最长为六个月。


// Update room lifetime
DateTimeOffset updatedValidFrom = DateTimeOffset.UtcNow;
DateTimeOffset updatedValidUntil = DateTimeOffset.UtcNow.AddDays(10);
CommunicationRoom updatedRoom = await roomsClient.UpdateRoomAsync(roomId, updatedValidFrom, updatedValidUntil, cancellationToken);

// UpdateRoom or UpdateRoomAsync methods can take UpdateRoomOptions type as an input parameter.
bool pstnDialOutEnabled = true;
UpdateRoomOptions updateRoomOptions = new UpdateRoomOptions()
{
    ValidFrom = validFrom,
    ValidUntil = validUntil,
    PstnDialOutEnabled = pstnDialOutEnabled,
};

updatedRoom = await roomsClient.UpdateRoomAsync(roomId, updateRoomOptions, cancellationToken);
Console.WriteLine("\nUpdated room with validFrom: " + updatedRoom.ValidFrom + ", validUntil: " + updatedRoom.ValidUntil + " and pstnDialOutEnabled: " + updatedRoom.PstnDialOutEnabled);

列出所有活动会议室

使用客户端上公开的 GetRoomsAsync 方法检索所有活动会议室。


// List all active rooms
AsyncPageable<CommunicationRoom> allRooms = roomsClient.GetRoomsAsync();
await foreach (CommunicationRoom currentRoom in allRooms)
{
    Console.WriteLine("\nFirst room id in all active rooms: " + currentRoom.Id);
    break;
}

添加新参与者或更新现有参与者

要将新参与者添加到 room,请使用客户端上公开的 AddParticipantsAsync 方法。


List<RoomParticipant> addOrUpdateParticipants = new List<RoomParticipant>();
// Update participant2 from Attendee to Consumer
RoomParticipant participant2 = new RoomParticipant(user2) { Role = ParticipantRole.Consumer };
// Add participant3
CommunicationUserIdentifier user3 = identityClient.CreateUser();
RoomParticipant participant3 = new RoomParticipant(user3) { Role = ParticipantRole.Attendee };
addOrUpdateParticipants.Add(participant2);
addOrUpdateParticipants.Add(participant3);

Response addOrUpdateParticipantsResponse = await roomsClient.AddOrUpdateParticipantsAsync(roomId, addOrUpdateParticipants);
Console.WriteLine("\nAdded or updated participants to room");

已添加到 room 的参与者有资格加入通话。 已更新的参与者将在通话中看到其新的 role 内容。

获取参与者列表

通过引用 roomId 检索现有 room 的参与者列表:


// Get list of participants in room
AsyncPageable<RoomParticipant> existingParticipants = roomsClient.GetParticipantsAsync(roomId);
Console.WriteLine("\nRetrieved participants from room: ");
await foreach (RoomParticipant participant in existingParticipants)
{
    Console.WriteLine($"{participant.CommunicationIdentifier.ToString()},  {participant.Role.ToString()}");
}

删除参与者

要从 room 中删除参与者并撤销其访问权限,请使用 RemoveParticipantsAsync 方法。


// Remove user from room
List<CommunicationIdentifier> removeParticipants = new List<CommunicationIdentifier>();
removeParticipants.Add(user2);

Response removeParticipantsResponse = await roomsClient.RemoveParticipantsAsync(roomId, removeParticipants);
Console.WriteLine("\nRemoved participants from room");

删除房间

若要解散现有 room,可以发出显式的删除请求。 所有 rooms 及其关联的资源在其有效期加上宽限期结束后会自动删除。


// Deletes the specified room
Response deleteRoomResponse = await roomsClient.DeleteRoomAsync(roomId);
Console.WriteLine("\nDeleted room with id: " + roomId);

运行代码

若要运行代码,请确保你位于 Program.cs 文件所在的目录中。


dotnet run

预期的输出描述了每个已完成的操作:


Azure Communication Services - Rooms Quickstart

Created a room with id: 99445276259151407

Retrieved room with id: 99445276259151407

Updated room with validFrom: 2023-05-11T22:11:46.784Z, validUntil: 2023-05-21T22:16:46.784Z and pstnDialOutEnabled: true

First room id in all active rooms: 99445276259151407

Added or updated participants to room

Retrieved participants from room:
8:acs:b6aada1f-0b1d-47ac-866f-91aae00a1d01_00000018-ac89-7c76-35f3-343a0d00e901, Presenter
8:acs:b6aada1f-0b1d-47ac-866f-91aae00a1d01_00000018-f00d-aa4b-0cf9-9c3a0d00543e, Consumer
8:acs:b6aada1f-0b1d-47ac-866f-91aae00a1d01_00000018-f00d-aaf2-0cf9-9c3a0d00543f, Attendee

Removed participants from room

Deleted room with id: 99445276259151407

参考文档

.NET SDK 引用REST API 引用中了解 Azure 通信服务会议室的完整功能集。

本快速入门帮助你开始使用 Azure 通信服务的房间资源。 room 是服务器管理的通信空间,供一组已知的固定参与者在预定的持续时间内进行协作。 房间概念文档介绍了 rooms 的更多详细信息和用例。

先决条件

代码示例

可以在 GitHub 上查看并下载本快速入门的示例代码。

设置

创建新的 Java 应用程序

在控制台窗口(例如 cmd、PowerShell 或 Bash)中,使用 mvn 命令创建名为 rooms-quickstart 的新控制台应用。 此命令将创建包含单个源文件 (Program.cs) 的简单“Hello World”Java 项目:App.java。

mvn archetype:generate -DgroupId=com.communication.quickstart -DartifactId=communication-quickstart -DarchetypeArtifactId=maven-archetype-quickstart -DarchetypeVersion=1.4 -DinteractiveMode=false

添加包

需要使用适用于 Java 版本 1.1.0 或更高版本的 Azure 通信室客户端库。

包括 BOM 文件

azure-sdk-bom 包含在你的项目中以依赖于库的通用 (GA) 版本。 在以下代码段中,将 {bom_version_to_target} 占位符替换为版本号。 若要了解有关 BOM 的详细信息,请参阅 Azure SDK BOM 自述文件

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>com.azure</groupId>
            <artifactId>azure-sdk-bom</artifactId>
            <version>{bom_version_to_target}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

然后在没有版本标记的依赖项部分中包含直接依赖项。

<dependencies>
  <dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-communication-rooms</artifactId>
  </dependency>
</dependencies>

包括直接依赖项

如果你想依赖 BOM 中不存在的特定版本的库,请按如下方式将直接依赖项添加到你的项目中。

<dependency>
  <groupId>com.azure</groupId>
  <artifactId>azure-communication-rooms</artifactId>
  <version>1.0.0-beta.1</version>
</dependency>

设置应用框架

转到 /src/main/java/com/communication/quickstart 目录并打开 App.java 文件。 添加以下代码:


package com.communication.rooms.quickstart;

import com.azure.communication.common.*;
import com.azure.communication.identity.*;
import com.azure.communication.identity.models.*;
import com.azure.core.credential.*;
import com.azure.communication.rooms.*;

import java.io.IOException;
import java.time.*;
import java.util.*;

public class App
{
    public static void main( String[] args ) throws IOException
    {
        System.out.println("Azure Communication Services - Rooms Quickstart");
        // Quickstart code goes here
    }
}

初始化房间客户端

创建一个新的 RoomsClient 对象,用于创建新的 rooms 并管理其属性和生命周期。 Communications Service 的连接字符串将用于对请求进行身份验证。 有关连接字符串的详细信息,请参阅此页


// Initialize the rooms client
// Find your Communication Services resource in the Azure portal
String connectionString = "<connection string>";
RoomsClient roomsClient = new RoomsClientBuilder().connectionString(connectionString).buildClient();

创建房间

设置会议室参与者

若要设置谁可以加入会议室,你需要拥有这些用户的标识列表。 可以按照此处的说明创建用户和颁发访问令牌。 或者,如果要按需创建用户,可以使用 CommunicationIdentityClient 进行创建。

若要使用 CommunicationIdentityClient,请添加以下包:

<dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-communication-identity</artifactId>
</dependency>

导入位于 App.java 文件顶部的包:

import com.azure.communication.identity.CommunicationIdentityClient;
import com.azure.communication.identity.CommunicationIdentityClientBuilder;

现在,CommunicationIdentityClient 可以初始化并用于创建用户:

CommunicationIdentityClient communicationIdentityClient = new CommunicationIdentityClientBuilder()
    .connectionString(connectionString)
    .buildClient();

CommunicationUserIdentifier user1 = communicationClient.createUser();
CommunicationUserIdentifier user2 = communicationClient.createUser();
CommunicationUserIdentifier user3 = communicationClient.createUser();

然后,通过引用这些用户来创建会议室参与者的列表:

//The default participant role is ParticipantRole.Attendee
RoomParticipant participant_1 = new RoomParticipant(user1);
RoomParticipant participant_2 = new RoomParticipant(user2);
RoomParticipant participant_3 = new RoomParticipant(user3);

List<RoomParticipant> roomParticipants = new ArrayList<RoomParticipant>();

roomParticipants.add(participant_1);
roomParticipants.add(participant_2.setRole(ParticipantRole.CONSUMER));

初始化会议室

使用在上述代码片段中定义的 roomParticipants 创建新的 room

OffsetDateTime validFrom = OffsetDateTime.now();
OffsetDateTime validUntil = validFrom.plusDays(30);
boolean pstnDialOutEnabled = false;

CreateRoomOptions createRoomOptions = new CreateRoomOptions()
    .setValidFrom(validFrom)
    .setValidUntil(validUntil)
    .setPstnDialOutEnabled(pstnDialOutEnabled)
    .setParticipants(roomParticipants);

CommunicationRoom roomCreated = roomsClient.createRoom(createRoomOptions);

System.out.println("\nCreated a room with id: " + roomCreated.getRoomId());

由于 rooms 是服务器端实体,因此你可能想要跟踪 roomId 并将其持久保存在所选的存储媒体中。 可以引用 roomId 来查看或更新 room 对象的属性。

为会议室启用 PSTN 拨出功能

默认情况下,每个 room 都禁用了 PSTN 拨出功能。 在创建时,通过将 pstnDialOutEnabled 参数定义为 true,可以为 room 启用 PSTN 拨出。 还可以通过为 pstnDialOutEnabled 参数发出更新请求来为 room 修改此功能。

boolean pstnDialOutEnabled = true;
// Create a room with PSTN dial out capability
CreateRoomOptions createRoomOptions = new CreateRoomOptions()
    .setPstnDialOutEnabled(pstnDialOutEnabled)

CommunicationRoom roomCreated = roomsClient.createRoom(createRoomOptions);
System.out.println("\nCreated a room with PSTN dial out enabled: " + roomCreated.getPstnDialOutEnabled());

// Update a room to enable or disable PSTN dial out capability
pstnDialOutEnabled = false;
UpdateRoomOptions updateRoomOptions = new UpdateRoomOptions()
    .setPstnDialOutEnabled(pstnDialOutEnabled);

CommunicationRoom roomUpdated = roomsClient.updateRoom(roomId, updateRoomOptions);
System.out.println("\nUpdated a room with PSTN dial out enabled: " + roomUpdated.getPstnDialOutEnabled());

获取现有房间的属性

通过引用 roomId 来检索现有 room 的详细信息:


// Retrieve the room with corresponding ID
CommunicationRoom roomResult = roomsClient.getRoom(roomId);

System.out.println("Retrieved room with id: " + roomResult.getRoomId());

更新房间的生存期

可以通过对 ValidFromValidUntil 参数发出更新请求来修改 room 的生存期。 一个房间的有效期最长为六个月。


OffsetDateTime validFrom = OffsetDateTime.now().plusDays(1);
OffsetDateTime validUntil = validFrom.plusDays(1);
boolean pstnDialOutEnabled = true;

UpdateRoomOptions updateRoomOptions = new UpdateRoomOptions()
    .setValidFrom(validFrom)
    .setValidUntil(validUntil)
    .setPstnDialOutEnabled(pstnDialOutEnabled);

CommunicationRoom roomResult = roomsClient.updateRoom(roomId, updateRoomOptions);

System.out.println("Updated room with validFrom: " + roomResult.getValidFrom() + ", validUntil: " + roomResult.getValidUntil() + " and pstnDialOutEnabled: " + roomResult.getPstnDialOutEnabled());

添加或更新参与者

要将参与者添加或更新到 room,请使用客户端上公开的 addOrUpdateParticipants 方法。


List<RoomParticipant> participantsToAddAOrUpdate = new ArrayList<>();

// Adding new participant
 participantsToAddAOrUpdate.add(participant_3.setRole(ParticipantRole.CONSUMER));

// Updating current participant
participantsToAddAOrUpdate.add(participant_2.setRole(ParticipantRole.PRESENTER));

AddOrUpdateParticipantsResult addOrUpdateParticipantsResult = roomsClient.addOrUpdateParticipants(roomId, participantsToAddAOrUpdate);

System.out.println("Participant(s) added/updated");

已添加到 room 的参与者有资格加入通话。

获取参与者列表

通过引用 roomId 检索现有 room 的参与者列表:


// Get list of participants
try {

PagedIterable<RoomParticipant> participants = roomsClient.listParticipants(roomId);

System.out.println("Participants:/n");

for (RoomParticipant participant : participants) {
    System.out.println(participant.getCommunicationIdentifier().getRawId() + " (" + participant.getRole() + ")");
   }
} catch (Exception ex) {
    System.out.println(ex);
}

删除参与者

要从 room 中删除参与者并撤销其访问权限,请使用 removeParticipants 方法。


// Remove a participant from the room
List<CommunicationIdentifier> participantsToRemove = new ArrayList<>();

participantsToRemove.add(participant_3.getCommunicationIdentifier());

RemoveParticipantsResult removeParticipantsResult = roomsClient.removeParticipants(roomId,participantsToRemove);

System.out.println("Participant(s) removed");

列出所有活动会议室

检索 Azure 通信服务资源下的所有活动 rooms

try {
    Iterable<PagedResponse<CommunicationRoom>> roomPages = roomsClient.listRooms().iterableByPage();

    System.out.println("Listing all the rooms IDs in the first two pages of the list of rooms:");

    int count = 0;
    for (PagedResponse<CommunicationRoom> page : roomPages) {
        for (CommunicationRoom room : page.getElements()) {
            System.out.println("\n" + room.getRoomId());
        }

        count++;
        if (count >= 2) {
            break;
        }
    }
} catch (Exception ex) {
    System.out.println(ex);
}

删除房间

若要解散现有 room,可以发出显式的删除请求。 所有 rooms 及其关联的资源在其有效期加上宽限期结束后会自动删除。


// Deletes the specified room
roomsClient.deleteRoomWithResponse(roomId, Context.NONE);
System.out.println("\nDeleted the room with ID: " + roomId);

运行代码

若要运行代码,请转到包含 pom.xml 文件的目录并编译程序。


mvn compile

然后生成包:


mvn package

执行应用。

mvn exec:java -D"exec.mainClass"="com.communication.rooms.quickstart" -D"exec.cleanupDaemonThreads"="false"

预期的输出描述了每个已完成的操作:


Azure Communication Services - Rooms Quickstart

Created a room with id:  99445276259151407

Retrieved room with id:  99445276259151407

Updated room with validFrom: 2023-05-11T22:11:46.784Z, validUntil: 2023-05-11T22:16:46.784Z and pstnDialOutEnabled: true

Participant(s) added/updated

Participants:
8:acs:b6aada1f-0b1d-47ac-866f-91aae00a1d01_00000018-ac89-7c76-35f3-343a0d00e901 (Attendee)
8:acs:b6aada1f-0b1d-47ac-866f-91aae00a1d01_00000018-ac89-7c76-35f3-343a0d00e902 (Consumer)

Participant(s) removed

Listing all the rooms IDs in the first two pages of the list of rooms: 
99445276259151407
99445276259151408
99445276259151409

Deleted the room with ID:  99445276259151407

参考文档

Java SDK 引用REST API 引用中了解 Azure 通信服务会议室的完整功能集。

本快速入门帮助你开始使用 Azure 通信服务的房间资源。 room 是服务器管理的通信空间,供一组已知的固定参与者在预定的持续时间内进行协作。 房间概念文档介绍了 rooms 的更多详细信息和用例。

先决条件

代码示例

可以在 GitHub 上查看并下载本快速入门的示例代码。

设置

创建新的 Python 应用程序

在终端或控制台窗口中,为应用程序创建一个新文件夹并导航到它。

mkdir acs-rooms-quickstart
cd acs-rooms-quickstart

安装包

需要使用适用于 Python 版本 1.1.0 或更高版本的 Azure 通信室客户端库。

在控制台提示符下,导航到包含 rooms.py 文件的目录,然后执行以下命令:

pip install azure-communication-rooms

设置应用框架

创建一个名为 rooms-quickstart.py 的新文件并添加基本程序结构。

import os
from datetime import datetime, timedelta
from azure.core.exceptions import HttpResponseError
from azure.communication.rooms import (
    RoomsClient,
    RoomParticipant,
    ParticipantRole
)

class RoomsQuickstart(object):
    print("Azure Communication Services - Rooms Quickstart")
    #room method implementations goes here

if __name__ == '__main__':
    rooms = RoomsQuickstart()

初始化房间客户端

创建一个新的 RoomsClient 对象,用于创建新的 rooms 并管理其属性和生命周期。 Communications Service 的连接字符串将用于对请求进行身份验证。 有关连接字符串的详细信息,请参阅此页

#Find your Communication Services resource in the Azure portal
connection_string = '<connection_string>'
rooms_client = RoomsClient.from_connection_string(connection_string)

创建房间

设置会议室参与者

若要设置谁可以加入会议室,你需要拥有这些用户的标识列表。 可以按照此处的说明创建用户和颁发访问令牌。 或者,如果要按需创建用户,可以使用 CommunicationIdentityClient 进行创建。

要使用 CommunicationIdentityClient,请安装以下包:

pip install azure-communication-identity

此外,在 rooms-quickstart.py 文件顶部导入包的命名空间:

from azure.communication.identity import (
    CommunicationIdentityClient
)

现在,CommunicationIdentityClient 可以初始化并用于创建用户:

# Create identities for users who will join the room
identity_client = CommunicationIdentityClient.from_connection_string(connection_string)
user1 = identity_client.create_user()
user2 = identity_client.create_user()
user3 = identity_client.create_user()

然后,通过引用这些用户来创建会议室参与者的列表:

participant_1 = RoomParticipant(communication_identifier=user1, role=ParticipantRole.PRESENTER)
participant_2 = RoomParticipant(communication_identifier=user2, role=ParticipantRole.CONSUMER)
participants = [participant_1, participant_2]

初始化会议室

使用在上述代码片段中定义的 participants 创建新的 room

# Create a room
valid_from = datetime.now()
valid_until = valid_from + timedelta(weeks=4)
pstn_dial_out_enabled = False

try:
    create_room = rooms_client.create_room(
        valid_from=valid_from,
        valid_until=valid_until,
        pstn_dial_out_enabled=pstn_dial_out_enabled,
        participants=participants
    )
    print("\nCreated a room with id: " + create_room.id)
except HttpResponseError as ex:
    print(ex)

由于 rooms 是服务器端实体,因此你可能想要跟踪 room.id 并将其持久保存在所选的存储媒体中。 可以引用 id 来查看或更新 room 对象的属性。

为会议室启用 PSTN 拨出功能

默认情况下,每个 room 都禁用了 PSTN 拨出功能。 在创建时,通过将 pstn_dial_out_enabled 参数定义为 true,可以为 room 启用 PSTN 拨出。 还可以通过为 pstn_dial_out_enabled 参数发出更新请求来为 room 修改此功能。

# Create a room with PSTN dial out capability
pstn_dial_out_enabled = True
create_room = rooms_client.create_room(pstn_dial_out_enabled=pstn_dial_out_enabled)
print("\nCreated room with pstn_dial_out_enabled: " + updated_room.pstn_dial_out_enabled)

# Update a room to enable or disable PSTN dial out capability
pstn_dial_out_enabled= False
updated_room = rooms_client.update_room(room_id=room_id, pstn_dial_out_enabled=pstn_dial_out_enabled)
print("\nUpdated room with pstn_dial_out_enabled: " + updated_room.pstn_dial_out_enabled)

获取现有房间的属性

通过引用 id 来检索现有 room 的详细信息:

# Retrieves the room with corresponding ID
room_id = create_room.id
try:
    get_room = rooms_client.get_room(room_id=room_id)
    print("\nRetrieved room with id: ", get_room.id)
except HttpResponseError as ex:
    print(ex)

更新房间的生存期

可以通过对 valid_fromvalid_until 参数发出更新请求来修改 room 的生存期。 一个房间的有效期最长为六个月。

# Update the lifetime of a room
valid_from =  datetime.now()
valid_until = valid_from + timedelta(weeks=7)
pstn_dial_out_enabled=True

try:
    updated_room = rooms_client.update_room(room_id=room_id, valid_from=valid_from, valid_until=valid_until, pstn_dial_out_enabled=pstn_dial_out_enabled)
     print("\nUpdated room with validFrom: " + updated_room.valid_from + ", validUntil: " + updated_room.valid_until + " and pstn_dial_out_enabled: " + updated_room.pstn_dial_out_enabled)
except HttpResponseError as ex:
    print(ex)

列出所有活动会议室

若要检索在资源下创建的所有活动会议室,请使用客户端上公开的 list_rooms 方法。

# List all active rooms
try:
    rooms = rooms_client.list_rooms()
    count = 0
    for room in rooms:
        if count == 1:
            break
        print("\nPrinting the first room in list"
            "\nRoom Id: " + room.id +
            "\nCreated date time: " + str(room.created_at) +
            "\nValid From: " + str(room.valid_from) + 
            "\nValid Until: " + str(room.valid_until) +
            "\nPSTN Dial-Out Enabled: " + str(room.pstn_dial_out_enabled))
        count += 1
except HttpResponseError as ex:
    print(ex)

添加或更新参与者

若要在 room 中添加新参与者或更新现有参与者,请使用客户端上公开的 add_or_update_participants 方法。

# Add or update participants in a room
try:
    # Update existing user2 from consumer to attendee
    participants = []
    participants.append(RoomParticipant(communication_identifier=user2, role=ParticipantRole.ATTENDEE))

    # Add new participant user3
    participants.append(RoomParticipant(communication_identifier=user3, role=ParticipantRole.CONSUMER))
    rooms_client.add_or_update_participants(room_id=room_id, participants=participants)
    print("\nAdd or update participants in room")

except HttpResponseError as ex:
    print('Error in adding or updating participants to room.', ex)

已添加到 room 的参与者有资格加入通话。

列出会议室中的参与者

通过引用 room_id 检索现有 room 的参与者列表:

# Get list of participants in room
try:
    participants = rooms_client.list_participants(room_id)
    print('\nParticipants in Room Id :', room_id)
    for p in participants:
        print(p.communication_identifier.properties['id'], p.role)
except HttpResponseError as ex:
    print(ex)

删除参与者

要从 room 中删除参与者并撤销其访问权限,请使用 remove_participants 方法。

# Remove Participants
try:
    participants = [user2]
    rooms_client.remove_participants(room_id=room_id, participants=participants)
    print("\nRemoved participants from room")

except HttpResponseError as ex:
    print(ex)

删除房间

若要解散现有 room,可以发出显式的删除请求。 所有 rooms 及其关联的资源在其有效期加上宽限期结束后会自动删除。

# Delete Room

rooms_client.delete_room(room_id=room_id)
print("\nDeleted room with id: " + room_id)

运行代码

若要运行代码,请确保你位于 rooms-quickstart.py 文件所在的目录中。


python rooms-quickstart.py

预期的输出描述了每个已完成的操作:


Azure Communication Services - Rooms Quickstart

Created a room with id:  99445276259151407

Retrieved room with id:  99445276259151407

Updated room with validFrom: 2023-05-03T00:00:00+00:00, validUntil: 2023-06-23T00:00:00+00:00 and pstn_dial_out_enabled: True

Printing the first room in list
Room Id: 99445276259151407
Created date time: 2023-05-03T00:00:00+00:00
Valid From: 2023-05-03T00:00:00+00:00
Valid Until: 2023-06-23T00:00:00+00:00
PSTN Dial-Out Enabled: True

Add or update participants in room

Participants in Room Id : 99445276259151407
8:acs:42a0ff0c-356d-4487-a288-ad0aad95d504_00000018-ef00-6042-a166-563a0d0051c1 Presenter
8:acs:42a0ff0c-356d-4487-a288-ad0aad95d504_00000018-ef00-6136-a166-563a0d0051c2 Consumer
8:acs:42a0ff0c-356d-4487-a288-ad0aad95d504_00000018-ef00-61fd-a166-563a0d0051c3 Attendee

Removed participants from room

Deleted room with id: 99445276259151407

参考文档

Python SDK 引用REST API 引用中了解 Azure 通信服务会议室的完整功能集。

本快速入门帮助你开始使用 Azure 通信服务的房间资源。 room 是服务器管理的通信空间,供一组已知的固定参与者在预定的持续时间内进行协作。 房间概念文档介绍了 rooms 的更多详细信息和用例。

先决条件

代码示例

可以在 GitHub 上查看并下载本快速入门的示例代码。

设置

新建 Web 应用程序

在终端或控制台窗口中,为应用程序创建一个新文件夹并导航到它。

mkdir acs-rooms-quickstart && cd acs-rooms-quickstart

运行 npm init 以使用默认设置创建 package.json 文件。

npm init -y

创建一个新文件 (index.js),我们将在其中添加本快速入门的代码。

安装包

需要使用适用于 JavaScript 版本 1.1.0 或更高版本的 Azure 通信室客户端库。

使用 npm install 命令安装适用于 JavaScript 的以下通信服务 SDK。

npm install @azure/communication-rooms --save

设置应用框架

index.js 文件中,添加以下代码。 我们将在 main 函数中添加本快速入门的代码。

const { RoomsClient } = require('@azure/communication-rooms');

const main = async () => {
  console.log("Azure Communication Services - Rooms Quickstart")

  // Quickstart code goes here

};

main().catch((error) => {
  console.log("Encountered an error");
  console.log(error);
})

初始化房间客户端

创建一个新的 RoomsClient 对象,用于创建新的 rooms 并管理其属性和生命周期。 Communications Service 的连接字符串将用于对请求进行身份验证。 有关连接字符串的详细信息,请参阅此页

main 函数内的 index.js 中添加以下代码。

const connectionString =
    process.env["COMMUNICATION_CONNECTION_STRING"] ||
    "endpoint=https://<resource-name>.communication.azure.com/;<access-key>";

// create RoomsClient
const roomsClient = new RoomsClient(connectionString);

创建房间

设置会议室参与者

若要设置谁可以加入会议室,你需要拥有这些用户的标识列表。 可以按照此处的说明创建用户和颁发访问令牌。 或者,如果要按需创建用户,可以使用 CommunicationIdentityClient 进行创建。

若要使用 CommunicationIdentityClient,请安装以下 npm 包:

npm install @azure/communication-identity --save

此外,请在 index.js 文件顶部添加以下必需的包:

const { CommunicationIdentityClient } = require('@azure/communication-identity');

现在,CommunicationIdentityClient 可以初始化并用于创建用户:

// create identities for users
const identityClient = new CommunicationIdentityClient(connectionString);
const user1 = await identityClient.createUserAndToken(["voip"]);
const user2 = await identityClient.createUserAndToken(["voip"]);

然后,通过引用这些用户来创建会议室参与者的列表:

const participants = [
  {
      id: user1.user,
      role: "Presenter",
  },
  {
    id: user2.user,
    role: "Consumer",
  }
]

初始化会议室

使用在上述代码片段中定义的 participants 创建新的 room

// Create a room
var validFrom = new Date(Date.now());
var validUntil = new Date(validFrom.getTime() + 60 * 60 * 1000);
var pstnDialOutEnabled = false;

const createRoomOptions = {
  validFrom,
  validUntil,
  pstnDialOutEnabled,
  participants
};

const createRoom = await roomsClient.createRoom(createRoomOptions);
const roomId = createRoom.id;
console.log("\nCreated a room with id: ", roomId);

由于 rooms 是服务器端实体,因此你可能想要跟踪 roomId 并将其持久保存在所选的存储媒体中。 可以引用 roomId 来查看或更新 room 对象的属性。

为会议室启用 PSTN 拨出功能

默认情况下,每个 room 都禁用了 PSTN 拨出功能。 在创建时,通过将 pstnDialOutEnabled 参数定义为 true,可以为 room 启用 PSTN 拨出。 还可以通过为 pstnDialOutEnabled 参数发出更新请求来为 room 修改此功能。

// Create a room with PSTN dial out capability
var pstnDialOutEnabled = true;
const createRoomOptions = {
  pstnDialOutEnabled,
};

const createRoom = await roomsClient.createRoom(createRoomOptions);
console.log("\nCreated a room with PSTN dial out enabled: ", createRoom.pstnDialOutEnabled);

// Update a room to enable or disable PSTN dial out capability
pstnDialOutEnabled = false;
const updateRoomOptions = {
  pstnDialOutEnabled,
};

const updateRoom = await roomsClient.updateRoom(roomId, updateRoomOptions);
console.log("\nUpdated a room with PSTN dial out enabled: ", updateRoom.pstnDialOutEnabled);

获取现有房间的属性

通过引用 roomId 来检索现有 room 的详细信息:

// Retrieve the room with corresponding ID
const getRoom = await roomsClient.getRoom(roomId);
console.log("\nRetrieved room with id: ", getRoom.id);

更新房间的生存期

可以通过对 validFromvalidUntil 参数发出更新请求来修改 room 的生存期。 一个房间的有效期最长为六个月。

// Update room lifetime
validFrom.setTime(validUntil.getTime());
validUntil.setTime(validFrom.getTime() + 5 * 60 * 1000);
pstnDialOutEnabled = true;
// request payload to update a room
const updateRoomOptions = {
  validFrom,
  validUntil,
  pstnDialOutEnabled,
};

const updateRoom = await roomsClient.updateRoom(roomId, updateRoomOptions);
console.log("\nUpdated room with validFrom: ", updateRoom.validFrom, ", validUntil: ", updateRoom.validUntil, " and pstnDialOutEnabled: ", updateRoom.pstnDialOutEnabled);

获取会议室列表

使用 listRooms 方法检索会议室列表:

const roomsList = await roomsClient.listRooms();
console.log("\nRetrieved list of rooms; printing first room:");
for await (const currentRoom of roomsList) {
  // access room data here
  console.log(currentRoom);
  break;
}

添加或更新参与者

要将新参与者添加到 room,请使用客户端上公开的 addOrUpdateParticipants 方法。 如果参与者已存在于聊天室中,则此方法还会更新参与者。

// Add and update participants
// request payload to add and update participants
const addOUpdateParticipantsList = [
  {
      id: user1.user,
      role: "Presenter",
  },
  {
    id: user2.user,
    role: "Consumer",
  }
]

// add user2 to the room and update user1 to Presenter role
await roomsClient.addOrUpdateParticipants(roomId, addOUpdateParticipantsList);
console.log("\nAdded and updated participants in the room");

已添加到 room 的参与者有资格加入通话。

获取参与者列表

通过引用 roomId 检索现有 room 的参与者列表:

const participantsList = await roomsClient.listParticipants(roomId);
console.log("\nRetrieved participants for room:");
for await (const participant of participantsList) {
  // access participant data here
  console.log(participant);
}

删除参与者

要从 room 中删除参与者并撤销其访问权限,请使用 removeParticipants 方法。

// Remove both users from the room
const removeParticipantsList = [user1.user, user2.user]

// remove both users from the room with the request payload
await roomsClient.removeParticipants(roomId, removeParticipantsList);
console.log("\nRemoved participants from room");

删除房间

若要解散现有 room,可以发出显式的删除请求。 所有 rooms 及其关联的资源在其有效期加上宽限期结束后会自动删除。

// Deletes the specified room
await roomsClient.deleteRoom(roomId);
console.log("\nDeleted room with id: ", roomId)

运行代码

若要运行代码,请确保你位于 index.js 文件所在的目录中。

node index.js

预期的输出描述了每个已完成的操作:

Azure Communication Services - Rooms QuickStart

Created a room with id:  99445276259151407

Retrieved room with id:  99445276259151407

Updated room with validFrom:  2023-05-11T22:11:46.784Z, validUntil:  2023-05-11T22:16:46.784Z and pstnDialOutEnabled: true

Retrieved list of rooms; printing first room:

{
  id: "99445276259151407",
  createdAt: "2023-05-11T22:11:50.784Z",
  validFrom: "2023-05-11T22:11:46.784Z",
  validUntil: "2023-05-11T22:16:46.784Z"
}

Added and updated participants in the room

Retrieved participants for room:
{
  id: {
    kind: 'communicationUser',
    communicationUserId: '8:acs:b6aada1f-0b1d-47ac-866f-91aae00a1d01_00000018-ac89-7c76-35f3-343a0d00e901'
  },
  role: 'Presenter'
}
{
  id: {
    kind: 'communicationUser',
    communicationUserId: '8:acs:b6aada1f-0b1d-47ac-866f-91aae00a1d01_00000018-ac89-7ccc-35f3-343a0d00e902'
  },
  role: 'Consumer'
}

Removed participants from room

Deleted room with id:  99445276259151407

参考文档

JavaScript SDK 引用REST API 引用中了解 Azure 通信服务会议室的完整功能集。

后续步骤

可以了解如何在创建并配置会议室后加入会议室通话

在本部分,你已了解如何执行以下操作:

  • 创建新房间
  • 获取房间的属性
  • 更新房间的属性
  • 删除房间

你可能还想要: