连接到媒体服务 v3 API - Node.jsConnect to Media Services v3 API - Node.js

媒体服务徽标 v3media services logo v3


备注

Google Widevine 内容保护服务目前在 Azure 中国区域不可用。Google Widevine content protection services are currently unavailable in the Azure China regions.

本文介绍如何使用服务主体登录方法连接到 Azure 媒体服务 v3 node.js SDK。This article shows you how to connect to the Azure Media Services v3 node.js SDK using the service principal sign-in method. 你将使用 media-services-v3-node-tutorials 示例存储库中的文件。You will work with files in the media-services-v3-node-tutorials samples repository. HelloWorld-ListAssets 示例包含用于连接的代码,并在帐户中列出资产。The HelloWorld-ListAssets sample contains the code for connecting then list Assets in the account.

先决条件Prerequisites

重要

查看 Azure 媒体服务命名约定,了解实体的重要命名限制。Review the Azure Media Services naming conventions to understand the important naming restrictions on entities.

克隆 Node.JS 示例存储库Clone the Node.JS samples repo

你将在 Azure 示例中使用一些文件。You will work with some files in Azure Samples. 克隆 Node.JS 示例存储库。Clone the Node.JS samples repository.

git clone https://github.com/Azure-Samples/media-services-v3-node-tutorials.git

安装包Install the packages

安装 @azure/arm-mediaservicesInstall @azure/arm-mediaservices

npm install @azure/arm-mediaservices

安装 @azure/ms-rest-nodeauthInstall @azure/ms-rest-nodeauth

请安装“@azure/ms-rest-nodeauth”的最低版本:“^3.0.0”。Please install minimum version of "@azure/ms-rest-nodeauth": "^3.0.0".

npm install @azure/ms-rest-nodeauth@"^3.0.0"

在此示例中,你将在 package.json 文件中使用以下包。For this example, you will use the following packages in the package.json file.

程序包Package 说明Description
@azure/arm-mediaservices Azure 媒体服务 SDK。Azure Media Services SDK.
为确保使用的是最新的 Azure 媒体服务包,请检查 npm install@azure/arm-mediaservicesTo make sure you are using the latest Azure Media Services package, check npm install @azure/arm-mediaservices.
@azure/ms-rest-nodeauth 使用服务主体或托管标识进行 AAD 身份验证时所必需的Required for AAD authentication using Service Principal or Managed Identity
@azure/storage-blob 存储 SDK。Storage SDK. 将文件上传到资产时使用。Used when uploading files into assets.
@azure/ms-rest-js 用于登录。Used to sign in.
@azure/storage-blob 用于将文件上传和下载到 Azure 媒体服务中的“资产”,以进行编码。Used to upload and download files into Assets in Azure Media Services for encoding.
@azure/abort-controller 与存储客户端一起用于超时长时间运行的下载操作Used along with the storage client to time out long running download operations

创建 package.json 文件Create the package.json file

  1. 使用偏好的编辑器创建一个 package.json 文件。Create a package.json file using your favorite editor.
  2. 打开该文件并粘贴以下代码:Open the file and paste the following code:
{
  "name": "media-services-node-sample",
  "version": "0.1.0",
  "description": "",
  "main": "./index.ts",
  "dependencies": {
    "@azure/arm-mediaservices": "^8.0.0",
    "@azure/abort-controller": "^1.0.2",
    "@azure/ms-rest-nodeauth": "^3.0.6",
    "@azure/storage-blob": "^12.4.0",
  }
}

使用 TypeScript 连接到 Node.js 客户端Connect to Node.js client using TypeScript

示例 .env 文件Sample .env file

将此文件的内容复制到名为 .env 的文件中。Copy the content of this file to a file named .env. 它应存储在工作存储库的根目录中。It should be stored at the root of your working repository. 这些是你在门户中媒体服务帐户的“API 访问”页中获得的值。These are the values you got from the API Access page for your Media Services account in the portal.

一旦创建了 .env 文件,就可以开始使用这些示例。Once you have created the .env file, you can start working with the samples.

# Values from the API Access page in the portal
AZURE_CLIENT_ID=""
AZURE_CLIENT_SECRET= ""
AZURE_TENANT_ID= ""

# Change this to match your AAD Tenant domain name. 
AAD_TENANT_DOMAIN = "microsoft.partner.onmschina.cn"

# Set this to your Media Services Account name, resource group it is contained in, and location
AZURE_MEDIA_ACCOUNT_NAME = ""
AZURE_LOCATION= ""
AZURE_RESOURCE_GROUP= ""

# Set this to your Azure Subscription ID
AZURE_SUBSCRIPTION_ID= ""

AZURE_ARM_AUDIENCE= "https://management.core.chinacloudapi.cn"
AZURE_ARM_ENDPOINT="https://management.chinacloudapi.cn"

# DRM Testing
DRM_SYMMETRIC_KEY="add random base 64 encoded string here"

运行示例应用程序 HelloWorld-ListAssetsRun the sample application HelloWorld-ListAssets

  1. 将目录更改为 AMSv3Samples 文件夹Change directory into the AMSv3Samples folder
cd AMSv3Samples
  1. 安装 packages.json 文件中使用的包。Install the packages used in the packages.json file.
npm install 
  1. 将目录更改为 HelloWorld-ListAssets 文件夹。Change directory into the HelloWorld-ListAssets folder.
cd HelloWorld-ListAssets
  1. 从 AMSv3Samples 文件夹中启动 Visual Studio Code。Launch Visual Studio Code from the AMSv3Samples Folder. 需要从“.vscode”文件夹和 tsconfig.json 文件所在的文件夹中启动This is required to launch from the folder where the ".vscode" folder and tsconfig.json files are located
cd ..
code .

打开 HelloWorld-ListAssets 的文件夹,然后在 Visual Studio Code 编辑器中打开 index.ts 文件。Open the folder for HelloWorld-ListAssets, and open the index.ts file in the Visual Studio Code editor.

在 index.ts 文件中,按 F5 启动调试器。While in the index.ts file, press F5 to launch the debugger. 如果你的资产已在帐户中,应会看到显示的资产列表。You should see a list of assets displayed if you have assets already in the account. 如果帐户为空,你将看到一个空列表。If the account is empty, you will see an empty list.

若要快速查看列出的资产,请使用门户上传几个视频文件。To quickly see assets listed, use the portal to upload a few video files. 将自动创建每个资产,然后再次运行此脚本以返回它们的名称。Assets will automatically be created each one and running this script again will then return their names.

详细了解 HelloWorld-ListAssets 示例A closer look at the HelloWorld-ListAssets sample

HelloWorld-ListAssets 示例说明了如何使用服务主体连接到媒体服务客户端,并列出帐户中的资产。The HelloWorld-ListAssets sample shows you how to connect to the Media Services client with a Service Principal and list Assets in the account. 有关其作用的详细说明,请参阅代码中的注释。See the comments in the code for a detailed explanation of what it does.

import * as msRestNodeAuth from "@azure/ms-rest-nodeauth";
import { AzureMediaServices } from '@azure/arm-mediaservices';
import { AzureMediaServicesOptions } from "@azure/arm-mediaservices/esm/models";
// Load the .env file if it exists
import * as dotenv from "dotenv";
dotenv.config();

export async function main() {
  // Copy the samples.env file and rename it to .env first, then populate it's values with the values obtained 
  // from your Media Services account's API Access page in the Azure portal.
  const clientId = process.env.AZURE_CLIENT_ID as string;
  const secret = process.env.AZURE_CLIENT_SECRET as string;
  const tenantDomain = process.env.AAD_TENANT_DOMAIN as string;
  const subscriptionId = process.env.AZURE_SUBSCRIPTION_ID as string;
  const resourceGroup = process.env.AZURE_RESOURCE_GROUP as string;
  const accountName = process.env.AZURE_MEDIA_ACCOUNT_NAME as string;

  let clientOptions: AzureMediaServicesOptions = {
    longRunningOperationRetryTimeout: 5, // set the time out for retries to 5 seconds
    noRetryPolicy: false // use the default retry policy.
  }

  const creds = await msRestNodeAuth.loginWithServicePrincipalSecret(clientId, secret, tenantDomain);
  const mediaClient = new AzureMediaServices(creds, subscriptionId, clientOptions);

  // List Assets in Account
  console.log("Listing Assets Names in account:")
  var assets = await mediaClient.assets.list(resourceGroup, accountName);

  assets.forEach(asset => {
    console.log(asset.name);
  });

  if (assets.odatanextLink) {
    console.log("There are more than 1000 assets in this account, use the assets.listNext() method to continue listing more assets if needed")
    console.log("For example:  assets = await mediaClient.assets.listNext(assets.odatanextLink)");
  }
}

main().catch((err) => {
  console.error("Error running sample:", err.message);
});

更多示例More Samples

以下示例可在存储库中获得The following samples are available in the repository

项目名称Project name 用例Use Case
Live/index.tsLive/index.ts 基本实时传送视频流示例。Basic live streaming example. 警告:在使用实时传送视频流时,请确保检查是否已清理所有资源,并且不再在门户中计费WARNING, make sure to check that all resources are cleaned up and no longer billing in portal when using live
StreamFilesSample/index.tsStreamFilesSample/index.ts 上传本地文件或从源 URL 编码的基本示例。Basic example for uploading a local file or encoding from a source URL. 示例演示如何使用存储 SDK 下载内容,并演示如何流式传输到播放机Sample shows how to use storage SDK to download content, and shows how to stream to a player
StreamFilesWithDRMSample/index.tsStreamFilesWithDRMSample/index.ts 演示如何使用 PlayReady DRM 进行编码和流式传输Demonstrates how to encode and stream using PlayReady DRM
VideoIndexerSample/index.tsVideoIndexerSample/index.ts 使用视频和音频分析器预设生成视频或音频文件中的元数据和见解的示例Example of using the Video and Audio Analyzer presets to generate metadata and insights from a video or audio file

另请参阅See also

后续步骤Next steps

浏览媒体服务 Node.js 参考文档并查看示例,了解如何将媒体服务 API 与 Node.js 配合使用。Explore the Media Services Node.js ref documentation and check out samples that show how to use Media Services API with node.js.