教學課程:透過媒體服務進行即時串流Tutorial: Stream live with Media Services

注意

雖然教學課程使用 .NET SDK 範例,但是 REST APICLI 或其他受支援 SDK 的一般步驟都相同。Even though the tutorial uses .NET SDK examples, the general steps are the same for REST API, CLI, or other supported SDKs.

在 Azure 媒體服務中,即時事件會負責處理即時串流內容。In Azure Media Services, Live Events are responsible for processing live streaming content. 即時事件會提供輸入端點 (內嵌 URL),接著您再提供給即時編碼器。A Live Event provides an input endpoint (ingest URL) that you then provide to a live encoder. 即時事件會從即時編碼器接收即時輸入資料流,再透過一或多個串流端點進行串流處理。The Live Event receives live input streams from the live encoder and makes it available for streaming through one or more Streaming Endpoints. 即時事件也會提供預覽端點 (預覽 URL),您可在進一步處理和傳遞之前先用來預覽及驗證您的資料流。Live Events also provide a preview endpoint (preview URL) that you use to preview and validate your stream before further processing and delivery. 本教學課程說明如何使用 .NET Core 建立即時事件的傳遞類型。This tutorial shows how to use .NET Core to create a pass-through type of a live event.

本教學課程說明如何:The tutorial shows you how to:

如果您沒有 Azure 訂用帳戶,請在開始前建立免費帳戶If you don't have an Azure subscription, create a free account before you begin.

PrerequisitesPrerequisites

需要有下列項目,才能完成教學課程:The following items are required to complete the tutorial:

  • 安裝 Visual Studio Code 或 Visual Studio。Install Visual Studio Code or Visual Studio.
  • 建立媒體服務帳戶Create a Media Services account.
    請務必記住您用於資源群組名稱和「媒體服務」帳戶名稱的值。Make sure to remember the values you use for the resource group name and Media Services account name.
  • 請依照使用 Azure CLI 存取 Azure 媒體服務 API 中的步驟,並儲存認證。Follow the steps in Access Azure Media Services API with the Azure CLI and save the credentials. 您必須使用這些認證來存取 API。You'll need to use them to access the API.
  • 用來廣播事件的相機或裝置 (例如筆記型電腦)。A camera or a device (like a laptop) that's used to broadcast an event.
  • 內部部署即時編碼器,其會將相機中的訊號轉換成資料流,再傳送至媒體服務即時串流服務;請參閱建議的內部部署即時編碼器An on-premises live encoder that converts signals from the camera to streams that are sent to the Media Services live streaming service, see recommended on-premises live encoders. 資料流的格式必須是 RTMPSmooth StreamingThe stream has to be in RTMP or Smooth Streaming format.

提示

請務必先檢閱使用媒體服務 v3 進行即時串流,再繼續操作。Make sure to review Live streaming with Media Services v3 before proceeding.

下載並設定範例Download and configure the sample

使用以下命令將包含串流 .NET 範例的 GitHub 存放庫複製到您的機器:Clone a GitHub repository that contains the streaming .NET sample to your machine using the following command:

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

即時串流範例位於 Live 資料夾中。The live streaming sample is located in the Live folder.

在您下載的專案中開啟 appsettings.jsonOpen appsettings.json in your downloaded project. 將值取代為您從存取 API 中取得的認證。Replace the values with the credentials you got from accessing APIs.

重要

此範例會對每個資源使用唯一尾碼。This sample uses a unique suffix for each resource. 如果您取消偵錯,或在應用程式執行完成之前加以終止,您的帳戶將會出現多個即時事件。If you cancel the debugging or terminate the app without running it through, you'll end up with multiple Live Events in your account.
請確實停止執行即時事件。Make sure to stop the running Live Events. 否則將會產生相關費用Otherwise, you'll be billed!

檢查執行即時串流的程式碼Examine the code that performs live streaming

本節將檢查 MediaV3LiveApp 專案的 Program.cs 檔案中所定義的函式。This section examines functions defined in the Program.cs file of the MediaV3LiveApp project.

此範例會為每個資源建立唯一的尾碼,因此,即使您執行此範例多次而未進行清除,也不會發生名稱衝突。The sample creates a unique suffix for each resource so that you don't have name collisions if you run the sample multiple times without cleaning up.

重要

此範例會對每個資源使用唯一尾碼。This sample uses a unique suffix for each resource. 如果您取消偵錯,或在應用程式執行完成之前加以終止,您的帳戶將會出現多個即時事件。If you cancel the debugging or terminate the app without running it through, you'll end up with multiple Live Events in your account.
請確實停止執行即時事件。Make sure to stop the running Live Events. 否則將會產生相關費用Otherwise, you'll be billed!

開始搭配使用媒體服務 API 與 .NET SDKStart using Media Services APIs with .NET SDK

若要開始搭配使用媒體服務 API 與 .NET,您需要建立 AzureMediaServicesClient 物件。To start using Media Services APIs with .NET, you need to create an AzureMediaServicesClient object. 若要建立物件,您需要提供必要的認證,讓用戶端使用 Azure AD 連線至 Azure。To create the object, you need to supply credentials needed for the client to connect to Azure using Azure AD. 在您於本文一開始複製的程式碼中,GetCredentialsAsync 函式會根據本機組態檔中提供的認證建立 ServiceClientCredentials 物件。In the code you cloned at the beginning of the article, the GetCredentialsAsync function creates the ServiceClientCredentials object based on the credentials supplied in local configuration file.

private static async Task<IAzureMediaServicesClient> CreateMediaServicesClientAsync(ConfigWrapper config)
{
    var credentials = await GetCredentialsAsync(config);

    return new AzureMediaServicesClient(config.ArmEndpoint, credentials)
    {
        SubscriptionId = config.SubscriptionId,
    };
}

建立即時事件Create a live event

本節說明如何建立傳遞類型的即時事件 (LiveEventEncodingType 設定為 [無])。This section shows how to create a pass-through type of Live Event (LiveEventEncodingType set to None). 如需可用的即時事件類型詳細資訊,請參閱即時事件類型For more information about the available types of Live Events, see Live Event types.

您可能想要在建立即時事件時指定下列各項:Some things that you might want to specify when creating the live event are:

  • 媒體服務位置。Media Services location.
  • 「實況活動」的串流通訊協定 (目前支援 RTMP 和 Smooth Streaming 通訊協定)。The streaming protocol for the Live Event (currently, the RTMP and Smooth Streaming protocols are supported).
    當「即時事件」或其相關「即時輸出」正在執行時,您無法變更通訊協定選項。You can't change the protocol option while the Live Event or its associated Live Outputs are running. 如果您需要不同的通訊協定,則應為每個串流通訊協定建立個別的「即時事件」。If you require different protocols, create separate Live Event for each streaming protocol.
  • 內嵌和預覽的 IP 限制。IP restrictions on the ingest and preview. 您可以定義獲允許將視訊內嵌到這個「實況活動」的 IP 位址。You can define the IP addresses that are allowed to ingest a video to this Live Event. 允許的 IP 位址可以指定為單一 IP 位址 (例如 ‘10.0.0.1’)、使用 IP 位址和 CIDR 子網路遮罩的 IP 範圍 (例如 ‘10.0.0.1/22’),或是使用 IP 位址和小數點十進位子網路遮罩的 IP 範圍 (例如 '10.0.0.1(255.255.252.0)')。Allowed IP addresses can be specified as either a single IP address (for example '10.0.0.1'), an IP range using an IP address and a CIDR subnet mask (for example, '10.0.0.1/22'), or an IP range using an IP address and a dotted decimal subnet mask (for example, '10.0.0.1(255.255.252.0)').
    如果未指定 IP 位址而且也未定義規則,則任何 IP 位址都不允許。If no IP addresses are specified and there's no rule definition, then no IP address will be allowed. 若要允許任何 IP 位址,請建立規則,並設定 0.0.0.0/0。To allow any IP address, create a rule and set 0.0.0.0/0.
    IP 位址必須採用下列其中一個格式:具有四個數字的 IpV4 位址或 CIDR 位址範圍。The IP addresses have to be in one of the following formats: IpV4 address with four numbers or CIDR address range.
  • 在建立事件時,您可以指定要自動啟動它。When creating the event, you can specify to autostart it.
    當自動啟動設為 true 時,即時事件將會在建立後隨即啟動。When autostart is set to true, the Live Event will be started after creation. 這意味著「即時事件」只要開始執行,就會立即開始計費。That means the billing starts as soon as the Live Event starts running. 您必須對「實況活動」資源明確呼叫「停止」,才能終止進一步計費。You must explicitly call Stop on the Live Event resource to halt further billing. 如需詳細資訊,請參閱實況活動狀態和計費For more information, see Live Event states and billing.
  • 針對要預測的內嵌 URL,設定「虛名」模式。For an ingest URL to be predictive, set the "vanity" mode. 如需詳細資訊,請參閱實況活動內嵌 URLFor detailed information, see Live Event ingest URLs.
Console.WriteLine($"Creating a live event named {liveEventName}");
Console.WriteLine();

// Note: When creating a LiveEvent, you can specify allowed IP addresses in one of the following formats:                 
//      IpV4 address with 4 numbers
//      CIDR address range

IPRange allAllowIPRange = new IPRange(
    name: "AllowAll",
    address: "0.0.0.0",
    subnetPrefixLength: 0
);

// Create the LiveEvent input IP access control.
LiveEventInputAccessControl liveEventInputAccess = new LiveEventInputAccessControl
{
    Ip = new IPAccessControl(
            allow: new IPRange[]
            {
                allAllowIPRange
            }
        )

};

// Create the LiveEvent Preview IP access control
LiveEventPreview liveEventPreview = new LiveEventPreview
{
    AccessControl = new LiveEventPreviewAccessControl(
        ip: new IPAccessControl(
            allow: new IPRange[]
            {
                allAllowIPRange
            }
        )
    )
};

// To get the same ingest URL for the same LiveEvent name:
// 1. Set vanityUrl to true so you have ingest like: 
//        rtmps://liveevent-hevc12-eventgridmediaservice-usw22.channel.media.azure.net:2935/live/522f9b27dd2d4b26aeb9ef8ab96c5c77           
// 2. Set accessToken to a desired GUID string (with or without hyphen)

LiveEvent liveEvent = new LiveEvent(
    location: mediaService.Location,
    description: "Sample LiveEvent for testing",
    vanityUrl: false,
    encoding: new LiveEventEncoding(
                // When encodingType is None, the service simply passes through the incoming video and audio layer(s) to the output
                // When the encodingType is set to Standard or Premium1080p, a live encoder is used to transcode the incoming stream
                // into multiple bit rates or layers. See https://go.microsoft.com/fwlink/?linkid=2095101 for more information
                encodingType: LiveEventEncodingType.None,
                presetName: null
            ),
    input: new LiveEventInput(LiveEventInputProtocol.RTMP, liveEventInputAccess),
    preview: liveEventPreview,
    streamOptions: new List<StreamOptionsFlag?>()
    {
        // Set this to Default or Low Latency
        // When using Low Latency mode, you must configure the Azure Media Player to use the 
        // quick start hueristic profile or you won't notice the change. 
        // In the AMP player client side JS options, set -  heuristicProfile: "Low Latency Heuristic Profile". 
        // To use low latency optimally, you should tune your encoder settings down to 1 second GOP size instead of 2 seconds.
        StreamOptionsFlag.LowLatency
    }
);

Console.WriteLine($"Creating the LiveEvent, be patient this can take time...");

// When autostart is set to true, the Live Event will be started after creation. 
// That means, the billing starts as soon as the Live Event starts running. 
// You must explicitly call Stop on the Live Event resource to halt further billing.
// The following operation can sometimes take awhile. Be patient.
liveEvent = await client.LiveEvents.CreateAsync(config.ResourceGroup, config.AccountName, liveEventName, liveEvent, autoStart: true);

取得內嵌 URLGet ingest URLs

建立即時事件之後,您即可取得將提供給即時編碼器的內嵌 URL。Once the Live Event is created, you can get ingest URLs that you'll provide to the live encoder. 編碼器會使用這些 URL 來輸入即時串流。The encoder uses these URLs to input a live stream.

string ingestUrl = liveEvent.Input.Endpoints.First().Url;
Console.WriteLine($"The ingest url to configure the on premise encoder with is:");
Console.WriteLine($"\t{ingestUrl}");
Console.WriteLine();

取得預覽 URLGet the preview URL

使用 previewEndpoint 來預覽並確認已實際接收來自編碼器的輸入。Use the previewEndpoint to preview and verify that the input from the encoder is actually being received.

重要

請先確定影片流向預覽 URL,再繼續操作。Make sure that the video is flowing to the Preview URL before continuing.

string previewEndpoint = liveEvent.Preview.Endpoints.First().Url;
Console.WriteLine($"The preview url is:");
Console.WriteLine($"\t{previewEndpoint}");
Console.WriteLine();

Console.WriteLine($"Open the live preview in your browser and use the Azure Media Player to monitor the preview playback:");
Console.WriteLine($"\thttps://ampdemo.azureedge.net/?url={previewEndpoint}&heuristicprofile=lowlatency");
Console.WriteLine();

建立及管理即時事件與即時輸出Create and manage Live Events and Live Outputs

讓資料流流入即時事件之後,便可建立資產、即時輸出及串流定位器來開始串流事件。Once you have the stream flowing into the Live Event, you can begin the streaming event by creating an Asset, Live Output, and Streaming Locator. 這將封存串流,並透過「串流端點」將它提供給檢視器。This will archive the stream and make it available to viewers through the Streaming Endpoint.

建立資產Create an Asset

建立供即時輸出使用的資產。Create an Asset for the Live Output to use.

Console.WriteLine($"Creating an asset named {assetName}");
Console.WriteLine();
Asset asset = await client.Assets.CreateOrUpdateAsync(config.ResourceGroup, config.AccountName, assetName, new Asset());

建立即時輸出Create a Live Output

「實況輸出」會在建立時開始,並在刪除時結束。Live Outputs start on creation and stop when deleted. 當您刪除即時輸出時,並不會刪除基礎資產和資產中的內容。When you delete the Live Output, you're not deleting the underlying Asset and content in the asset.

string manifestName = "output";
Console.WriteLine($"Creating a live output named {liveOutputName}");
Console.WriteLine();

LiveOutput liveOutput = new LiveOutput(assetName: asset.Name, manifestName: manifestName, archiveWindowLength: TimeSpan.FromMinutes(10));
liveOutput = await client.LiveOutputs.CreateAsync(config.ResourceGroup, config.AccountName, liveEventName, liveOutputName, liveOutput);

建立串流定位器Create a Streaming Locator

注意

建立媒體服務帳戶時,預設串流端點會新增至已停止狀態的帳戶。When your Media Services account is created, a default streaming endpoint is added to your account in the Stopped state. 若要開始串流內容並利用動態封裝和動態加密功能,您想要串流內容的串流端點必須處於執行中狀態。To start streaming your content and take advantage of dynamic packaging and dynamic encryption, the streaming endpoint from which you want to stream content has to be in the Running state.

當您已使用串流定位器發行即時輸出資產時,即時事件 (最長為 DVR 時段長度) 將繼續可檢視,直到串流定位器到期或遭到刪除,視孰者為早。When you publish the Live Output asset using a Streaming Locator, the Live Event (up to the DVR window length) will continue to be viewable until the Streaming Locator's expiry or deletion, whichever comes first.

Console.WriteLine($"Creating a streaming locator named {streamingLocatorName}");
Console.WriteLine();

StreamingLocator locator = new StreamingLocator(assetName: asset.Name, streamingPolicyName: PredefinedStreamingPolicy.ClearStreamingOnly);
locator = await client.StreamingLocators.CreateAsync(config.ResourceGroup, config.AccountName, streamingLocatorName, locator);

// Get the default Streaming Endpoint on the account
StreamingEndpoint streamingEndpoint = await client.StreamingEndpoints.GetAsync(config.ResourceGroup, config.AccountName, streamingEndpointName);

// If it's not running, Start it. 
if (streamingEndpoint.ResourceState != StreamingEndpointResourceState.Running)
{
    Console.WriteLine("Streaming Endpoint was Stopped, restarting now..");
    await client.StreamingEndpoints.StartAsync (config.ResourceGroup, config.AccountName, streamingEndpointName);
}

// Get the url to stream the output
ListPathsResponse paths = await client.StreamingLocators.ListPathsAsync(resourceGroupName, accountName, locatorName);

foreach (StreamingPath path in paths.StreamingPaths)
{
    UriBuilder uriBuilder = new UriBuilder();
    uriBuilder.Scheme = "https";
    uriBuilder.Host = streamingEndpoint.HostName;

    uriBuilder.Path = path.Paths[0];
    // Get the URL from the uriBuilder: uriBuilder.ToString()
}

清除媒體服務帳戶中的資源Cleaning up resources in your Media Services account

如果您完成串流處理事件,而且想要清除先前佈建的資源,請依照下列程序操作:If you're done streaming events and want to clean up the resources provisioned earlier, follow the following procedure:

  • 停止從編碼器發送串流。Stop pushing the stream from the encoder.
  • 停止即時事件。Stop the Live Event. 即時事件在停止之後,就不會產生任何費用。Once the Live Event is stopped, it won't incur any charges. 當您需要重新啟動它時,它會具有相同的內嵌 URL,因此您不需要重新設定編碼器。When you need to start it again, it will have the same ingest URL so you won't need to reconfigure your encoder.
  • 除非您想要繼續將即時事件封存為隨選串流,否則您可以停止「串流端點」。You can stop your Streaming Endpoint, unless you want to continue to provide the archive of your live event as an on-demand stream. 如果即時事件處於已停止狀態,就不會產生任何費用。If the Live Event is in a stopped state, it won't incur any charges.
private static async Task CleanupLiveEventAndOutputAsync(IAzureMediaServicesClient client, string resourceGroup, string accountName, string liveEventName)
{
    try
    {
        LiveEvent liveEvent = await client.LiveEvents.GetAsync(resourceGroup, accountName, liveEventName);

        if (liveEvent != null)
        {
            if (liveEvent.ResourceState == LiveEventResourceState.Running)
            {
                // If the LiveEvent is running, stop it and have it remove any LiveOutputs
                await client.LiveEvents.StopAsync(resourceGroup, accountName, liveEventName, removeOutputsOnStop: true);
            }

            // Delete the LiveEvent
            await client.LiveEvents.DeleteAsync(resourceGroup, accountName, liveEventName);
        }
    }
    catch (ApiErrorException e)
    {
        Console.WriteLine("CleanupLiveEventAndOutputAsync -- Hit ApiErrorException");
        Console.WriteLine($"\tCode: {e.Body.Error.Code}");
        Console.WriteLine($"\tCode: {e.Body.Error.Message}");
        Console.WriteLine();
    }
}
private static async Task CleanupLocatorandAssetAsync(IAzureMediaServicesClient client, string resourceGroup, string accountName, string streamingLocatorName, string assetName)
{
    try
    {
        // Delete the Streaming Locator
        await client.StreamingLocators.DeleteAsync(resourceGroup, accountName, streamingLocatorName);

        // Delete the Archive Asset
        await client.Assets.DeleteAsync(resourceGroup, accountName, assetName);
    }
    catch (ApiErrorException e)
    {
        Console.WriteLine("CleanupLocatorandAssetAsync -- Hit ApiErrorException");
        Console.WriteLine($"\tCode: {e.Body.Error.Code}");
        Console.WriteLine($"\tCode: {e.Body.Error.Message}");
        Console.WriteLine();
    }
}

監看事件Watch the event

若要監看事件,請複製您在執行「建立串流定位器」中說明的程式碼時所取得的串流 URL。To watch the event, copy the streaming URL that you got when you ran code described in Create a Streaming Locator. 您可以使用您選擇的媒體播放器。You can use a media player of your choice. 您可以使用 https://ampdemo.azureedge.net 上的 Azure 媒體播放器來測試您的資料流。Azure Media Player is available to test your stream at https://ampdemo.azureedge.net.

即時事件會在停止時將事件自動轉換為點播內容。Live Event automatically converts events to on-demand content when stopped. 只要您未刪除資產,即使在停止並刪除事件之後,使用者還是可以視需求將您封存的內容以影片的形式進行串流。Even after you stop and delete the event, users can stream your archived content as a video on demand for as long as you don't delete the asset. 由事件使用中的資產無法刪除;必須先刪除事件。An asset can't be deleted if it's used by an event; the event must be deleted first.

清除資源Clean up resources

如果您不再需要資源群組中的任何資源 (包含您為教學課程建立的媒體服務和儲存體帳戶),請將稍早建立的資源群組刪除。If you no longer need any of the resources in your resource group, including the Media Services and storage accounts you created for this tutorial, delete the resource group you created earlier.

執行下列 CLI 命令:Execute the following CLI command:

az group delete --name amsResourceGroup

重要

讓即時事件處於執行狀態將會產生費用。Leaving the Live Event running incurs billing costs. 請注意,如果專案/程式失效或因故關閉,即時事件可能會在計費狀態下持續執行。Be aware, if the project/program crashes or is closed out for any reason, it could leave the Live Event running in a billing state.

提出問題、提供意見反應、取得更新Ask questions, give feedback, get updates

請參閱 Azure 媒體服務社群文章,以了解詢問問題、提供意見反應及取得媒體服務相關更新的不同方式。Check out the Azure Media Services community article to see different ways you can ask questions, give feedback, and get updates about Media Services.

後續步驟Next steps

串流檔案Stream files