チュートリアル: .NET 7.0 を使用して Media Services でライブストリーミングする

Media Services ロゴ v3


警告

Azure Media Services は、2024 年 6 月 30 日に廃止されます。 詳細については、「 AMS 廃止ガイド」を参照してください。

Azure Media Services では、ライブ イベントがライブ ストリーミング コンテンツの処理を受け持ちます。 ライブ イベントは入力エンドポイントであり、その取り込み URL をライブ エンコーダーに対して指定します。 ライブ イベントは、RTMP/S または Smooth Streaming プロトコルを使用してライブ エンコーダーから入力ストリームを受信し、1 つ以上の ストリーミング エンドポイントを介したストリーミングに使用できるようにします。 また、ストリームはあらかじめプレビューし、確認したうえで処理、配信しますが、ライブ イベントはその際に使用するプレビュー エンドポイント (プレビュー URL) も提供します。

このチュートリアルでは、.NET 7.0 を使用して パススルー ライブ イベントを作成する方法について説明します。 パススルー ライブ イベントは、オンプレミスでマルチビットレートの GOP アラインエンコードが可能なエンコーダーがある場合に便利です。 クラウド コストを削減する方法です。 帯域幅を減らし、マルチビットレート エンコードのために単一ビットレート ストリームをクラウドに送信する場合は、720P または 1080P エンコード プリセットでトランスコーディング ライブ イベントを使用できます。

このチュートリアルでは、次のことについて説明します。

  • サンプル プロジェクトをダウンロードします。
  • ライブ ストリーミングを実行するコードを確認する。
  • Media Player デモ サイトで Azure Media Player を使用してイベントを視聴する。
  • ライブ イベントを監視するように Event Grid を設定します。
  • リソースをクリーンアップする。

前提条件

このチュートリアルを完了するには、以下のものが必要です。

ライブ ストリーミング ソフトウェアには、次の項目も必要です。

  • イベントのブロードキャストに使用するカメラまたはデバイス (ラップトップなど)。
  • カメラ ストリームをエンコードし、Real-Time メッセージング プロトコル (RTMP/S) を介して Media Services ライブ ストリーミング サービスに送信するオンプレミスソフトウェア エンコーダー。 詳細については、「おすすめのライブ ストリーミング エンコーダー」を参照してください。 ストリームは、RTMP/S または Smooth Streaming 形式である必要があります。 このサンプルでは、Open Broadcaster Software (OBS) Studio を使用して RTMP/S を取り込みエンドポイントにブロードキャストすることを前提としています。 OBS Studio をインストールします。
  • または、OBS クイック スタートを試して、最初にAzure portalを使用してプロセス全体をテストすることもできます。

Event Grid と Event Hubs を使用してライブ イベントを監視するには、次の操作を行います。 1. Azure portalまたは 1 を使用して、Event Grid を使用して Media Services イベントを作成および監視する方法に関するページの手順に従います。この記事の「Event Grid と Event Hubs を使用したライブ イベントの監視」セクションで、このチュートリアルの終わり近くの手順に従います。

ヒント

先に進む前に、「Azure Media Services v3 を使用したライブ ストリーミング」を確認してください。

サンプルをダウンロードして構成する

次のコマンドを使用して、ライブストリーミングの .NET サンプルが含まれる GitHub リポジトリを自分のマシンにクローンします。

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

ライブ ストリーミング サンプルは、 Live/LiveEventWithDVR フォルダーにあります。

ダウンロードしたプロジェクトでを開きます appsettings.json 。 値をアカウント名、サブスクリプション ID、リソース グループ名に置き換えます。

重要

このサンプルでは、各リソースに一意のサフィックスを使用します。 デバッグを取り消した場合、または完全に実行せずにアプリを終了した場合、アカウントに複数のライブ イベントが作成されます。 実行中のライブ イベントを必ず停止してください。 そうしないと、"料金が発生" します。

.NET SDK で Media Services API の使用を開始する

Program.csは、 のオプション appsettings.jsonを使用して、Media Services アカウント リソースへの参照を作成します。

var mediaServicesResourceId = MediaServicesAccountResource.CreateResourceIdentifier(
    subscriptionId: options.AZURE_SUBSCRIPTION_ID.ToString(),
    resourceGroupName: options.AZURE_RESOURCE_GROUP,
    accountName: options.AZURE_MEDIA_SERVICES_ACCOUNT_NAME);
var credential = new DefaultAzureCredential(includeInteractiveCredentials: true);
var armClient = new ArmClient(credential);
var mediaServicesAccount = armClient.GetMediaServicesAccountResource(mediaServicesResourceId);

ライブ イベントを作成する

このセクションでは、ライブ イベントの パススルー 型を作成する方法を示します (LiveEventEncodingType を None に設定)。 使用可能なライブ イベントの種類については、「ライブ イベントの種類」のセクションを参照してください。 取り込み帯域幅全体を減らしたい場合、またはオンプレミスのマルチビットレート トランスコーダーがない場合は、720p または 1080p アダプティブ ビットレート クラウド エンコードにライブ トランスコード イベントを使用できます。

ライブ イベントを作成するときに、次の項目を指定したい場合もあります。

  • ライブ イベントの取り込みプロトコル。 現在、RTMPS プロトコルと Smooth Streaming プロトコルがサポートされています。 ライブ イベントの実行中にプロトコル オプションを変更することはできません。 別のプロトコルが必要な場合は、ストリーミング プロトコルごとに別のライブ イベントを作成します。

  • 取り込みやプレビューの IP 制限。 このライブ イベントへのビデオの取り込みが許可される IP アドレスを定義できます。 許可される IP アドレスは、これらのいずれかとして指定できます。

    • 1 つの IP アドレス (10.0.0.1 や 2001:db8::1 など)

    • IP アドレスとクラスレス Inter-Domain ルーティング (CIDR) サブネット マスクを使用する IP 範囲 (10.0.0.1/22 や 2001:db8::/48 など)

    • IP アドレスとドット付き 10 進サブネット マスクを使用する IP 範囲 (例: 10.0.0.1 255.255.252.0)

      IP アドレスが指定されておらず、規則の定義もない場合は、どの IP アドレスも許可されません。 任意の IP アドレスを許可するには、ルールを作成し、0.0.0.0/0 と ::/0 を設定します。 IP アドレスは、4 つの数値または CIDR アドレス範囲を持つ IPv4 または IPv6 アドレスのいずれかの形式である必要があります。 詳細については、「 IP 許可リストを使用して DRM ライセンスと AES キー配信へのアクセスを制限する」を参照してください。

  • イベントの作成時の自動開始。 自動開始が true に設定されている場合、ライブ イベントは作成後に開始されます。 つまり、ライブ イベントの実行が開始されるとすぐに課金が開始されます。 それ以上の課金を停止するには、ライブ イベント リソースの Stop を明示的に呼び出す必要があります。 詳細については、ライブ イベントの状態と課金に関するページを参照してください。

    各種のスタンバイ モードも利用できます。スタンバイ モードを使うと、実行中状態にすばやく移行できる低コストの "割り当て済み" 状態でライブ イベントを開始できます。 これは、ストリーム配信者にチャネルをすばやく配布する必要があるホット プールなどの状況に役立ちます。

  • 静的ホスト名と一意の GUID。 取り込み URL を予測可能で、ハードウェア ベースのライブ エンコーダーで保守しやすくするには、 プロパティを useStaticHostname true に設定します。 詳細については、「ライブ イベントの取り込み URL」のセクションを参照してください。

    var liveEvent = await mediaServicesAccount.GetMediaLiveEvents().CreateOrUpdateAsync(
        WaitUntil.Completed,
        liveEventName,
        new MediaLiveEventData(mediaServicesAccount.Get().Value.Data.Location)
        {
            Description = "Sample Live Event from the .NET SDK sample",
            UseStaticHostname = true,
            // 1) Set up the input settings for the Live event...
            Input = new LiveEventInput(streamingProtocol: LiveEventInputProtocol.Rtmp)
            {
                StreamingProtocol = LiveEventInputProtocol.Rtmp,
                AccessToken = "acf7b6ef-8a37-425f-b8fc-51c2d6a5a86a", // used to make the ingest URL unique
                KeyFrameIntervalDuration = TimeSpan.FromSeconds(2),
                IPAllowedIPs =
                {
                    new IPRange
                    {
                        Name = "AllowAllIpV4Addresses",
                        Address = IPAddress.Parse("0.0.0.0"),
                        SubnetPrefixLength = 0
                    },
                    new IPRange
                    {
                        Name = "AllowAllIpV6Addresses",
                        Address = IPAddress.Parse("0::"),
                        SubnetPrefixLength = 0
                    }
                }
            },
            // 2) Set the live event to use pass-through or cloud encoding modes...
            Encoding = new LiveEventEncoding()
            {
                EncodingType = LiveEventEncodingType.PassthroughBasic
            },
            // 3) Set up the Preview endpoint for monitoring
            Preview = new LiveEventPreview
            {
                IPAllowedIPs =
                {
                    new IPRange()
                    {
                        Name = "AllowAllIpV4Addresses",
                        Address = IPAddress.Parse("0.0.0.0"),
                        SubnetPrefixLength = 0
                    },
                    new IPRange()
                    {
                        Name = "AllowAllIpV6Addresses",
                        Address = IPAddress.Parse("0::"),
                        SubnetPrefixLength = 0
                    }
                }
            },
            // 4) Set up more advanced options on the live event. Low Latency is the most common one. Set
            //    this to Default or Low Latency. When using Low Latency mode, you must configure the Azure
            //    Media Player to use the quick start heuristic 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.
            StreamOptions =
            {
                StreamOptionsFlag.LowLatency
            },
            // 5) Optionally enable live transcriptions if desired. This is only supported on
            //    PassthroughStandard, and the transcoding live event types. It is not supported on Basic
            //    pass-through type.
            // WARNING: This is extra cost, so please check pricing before enabling.
            //Transcriptions =
            //{
            //    new LiveEventTranscription
            //    {
            //        // The value should be in BCP-47 format (e.g: 'en-US'). See https://go.microsoft.com/fwlink/?linkid=2133742
            //        Language = "en-us",
            //        TrackName = "English" // set the name you want to appear in the output manifest
            //    }
            //}
        },
        autoStart: false);
    

取り込み URL の取得

ライブ イベントの作成後、ライブ エンコーダーに提供する取り込み URL を取得できます。 エンコーダーは、これらの URL を使用して、ライブ ストリームを入力します。

// Get the RTMP ingest URL. The endpoints is a collection of RTMP primary and secondary,
// and RTMPS primary and secondary URLs.
Console.WriteLine($"The RTMP ingest URL to enter into OBS Studio is:");
Console.WriteLine(liveEvent.Data.Input.Endpoints.First(x => x.Uri.Scheme == "rtmps").Uri);
Console.WriteLine("Make sure to enter a Stream Key into the OBS Studio settings. It can be");
Console.WriteLine("any value or you can repeat the accessToken used in the ingest URL path.");
Console.WriteLine();

プレビュー URL を取得する

プレビューして、エンコーダーからの入力が受信されていることを確認するには、previewEndpoint を使用します。

重要

続行する前に、ビデオがプレビュー URL に送信されていることを確認してください。

// Use the previewEndpoint to preview and verify that the input from the encoder is actually
// being received The preview endpoint URL also support the addition of various format strings
// for HLS (format=m3u8-cmaf) and DASH (format=mpd-time-cmaf) for example. The default manifest
// is Smooth.
string previewEndpoint = liveEvent.Data.Preview.Endpoints.First().Uri.ToString();
Console.WriteLine($"The preview URL is:");
Console.WriteLine(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($"https://ampdemo.azureedge.net/?url={HttpUtility.UrlEncode(previewEndpoint)}&heuristicprofile=lowlatency");
Console.WriteLine();
Console.WriteLine("Start the live stream now, sending the input to the ingest URL and verify");
Console.WriteLine("that it is arriving with the preview URL.");
Console.WriteLine("IMPORTANT: Make sure that the video is flowing to the Preview URL before continuing!");
Console.WriteLine("Press enter to continue...");
Console.ReadLine();

ライブ イベントとライブ出力を作成して管理する

オンプレミス エンコーダーからのライブ ストリームがライブ イベントにストリーミングされたら、アセット、ライブ出力、ストリーミング ロケーターを作成してライブ イベントを開始できます。 ストリームはアーカイブされ、ストリーミング エンドポイントを介して閲覧者が利用できます。

次のセクションでは、アセットとライブ出力の作成手順を説明します。

アセットを作成する

ライブ出力で使用されるアセットを作成します。

// Create an Asset for the Live Output to use. Think of this as the "tape" that will be recorded
// to. The asset entity points to a folder/container in your Azure Storage account
Console.Write($"Creating the output Asset '{assetName}'...".PadRight(60));
var asset = (await mediaServicesAccount.GetMediaAssets().CreateOrUpdateAsync(
    WaitUntil.Completed,
    assetName,
    new MediaAssetData
    {
        Description = "My video description"
    })).Value;
Console.WriteLine("Done");

ライブ出力を作成する

ライブ出力は、作成されると開始し、削除されると停止します。 ライブ出力を削除しても、アセット内の出力アセットまたはコンテンツは削除されません。 記録を含む資産は、存在し、それに関連付けられているストリーミング ロケーターがある限り、オンデマンド ストリーミングで使用できます。

// Create the Live Output - think of this as the "tape recorder for the live event". Live
// outputs are optional, but are required if you want to archive the event to storage, use the
// asset for on-demand playback later, or if you want to enable cloud DVR time-shifting. We will
// use the asset created above for the "tape" to record to.
Console.Write($"Creating Live Output...".PadRight(60));
var liveOutput = (await liveEvent.GetMediaLiveOutputs().CreateOrUpdateAsync(
    WaitUntil.Completed,
    liveOutputName,
    new MediaLiveOutputData
    {
        AssetName = asset.Data.Name,
        // The HLS and DASH manifest file name. This is recommended to
        // set if you want a deterministic manifest path up front.
        // archive window can be set from 3 minutes to 25 hours.
        // Content that falls outside of ArchiveWindowLength is
        // continuously discarded from storage and is non-recoverable.
        // For a full event archive, set to the maximum, 25 hours.
        ManifestName = manifestName,
        ArchiveWindowLength = TimeSpan.FromHours(1)
    })).Value;
Console.WriteLine("Done");

ストリーミング ロケーターを作成する

Note

Media Services アカウントの作成時に、既定のストリーミング エンドポイントが停止状態でアカウントに追加されます。 コンテンツのストリーミングを開始し、ダイナミック パッケージと動的暗号化を活用するには、コンテンツのストリーミング元のストリーミング エンドポイントが実行中状態である必要があります。

ストリーミング ロケーターを作成して資産を発行します。 ライブ イベント (DVR ウィンドウの長さまで) は、ストリーミング ロケーターの有効期限または削除のいずれか早い方まで表示できます。 これは、視聴者がライブおよびオンデマンドで視聴できるようにビデオを利用できるようにする方法です。 ライブ イベントが完了し、ライブ出力が削除されたときに、ライブ イベント、DVR ウィンドウ、またはオンデマンド資産をwatchするために、同じ URL を使用できます。

var streamingLocator = (await mediaServicesAccount.GetStreamingLocators().CreateOrUpdateAsync(
    WaitUntil.Completed,
    streamingLocatorName,
    new StreamingLocatorData
    {
        AssetName = asset.Data.Name,
        StreamingPolicyName = "Predefined_ClearStreamingOnly",
        Filters =
        {
            filter.Data.Name
        }
    })).Value;

イベントの視聴

コードを実行します。 出力ストリーミング URL を使用して、ライブ イベントをwatchします。 ストリーミング ロケーターの URL をコピーします。 任意のメディア プレーヤーを使用できます。 Media Player デモ サイトを使用して、ストリームをテストできます。 URL フィールドに URL を入力し、[ プレーヤーの更新] を選択します。

Event Grid と Event Hubs を使用したライブ イベントの監視

サンプル プロジェクトでは、Event Grid と Event Hubs を使用してライブ イベントを監視できます。 Event Grid を設定して使用するには、次を使用します。

監視を有効にするには:

  1. Azure portalを使用して Event Hubs 名前空間と Event Hubs を作成する
    1. Azure portalの上部にあるテキスト ボックスを使用して、"Event Hubs" を検索します。
    2. 一覧から [Event Hub] を選択し、指示に従って Event Hubs 名前空間を作成します。
    3. Event Hubs 名前空間リソースに移動します。
    4. ポータル メニューの [エンティティ] セクションから [Event Hubs] を選択します。
    5. Event Hubs 名前空間に Event Hubs を作成します。
    6. Event Hubs リソースに移動します。
    7. [ アクセス制御 ]、[ 追加]、[ ロールの割り当ての追加] の順に選択します。
    8. Azure Event Hubs Data Receiver を選択し、自分へのアクセス権を付与します。
    9. [ アクセス制御 ]、[ 追加]、[ ロールの割り当ての追加] の順に選択します。
    10. Azure Event Hubs データ送信者を選択し、Media Services アカウント用に作成されたマネージド ID に付与します。
  2. Azure portalを使用して Azure Storage アカウントを作成します。
    1. ストレージ アカウントを作成したら、ストレージ アカウント リソースに移動します。
    2. [ アクセス制御 ]、[ 追加]、[ ロールの割り当ての追加] の順に選択します。
    3. [ストレージ BLOB データ共同作成者] を選択し、このアクセス権を自分に付与します。
  3. イベント サブスクリプションを作成する
    1. Media Services アカウントに移動します。
    2. ポータル メニューから [ イベント ] を選択します。
    3. [+ イベント サブスクリプション] を選択します。
    4. サブスクリプション名とシステムアーティクル名を入力します。
    5. [エンドポイントの種類] をEvent Hub設定します。
    6. Event Hubs を以前に作成した Event Hubs に設定し、マネージド ID を、以前に Event Hubs への送信者アクセス権が付与された ID に設定します
  4. appsetttings.json ファイルを更新します。
    1. EVENT_HUB_NAMESPACE名前空間の完全な名前に設定します。 これは に myeventhub.servicebus.windows.net似ているはずです。
    2. EVENT_HUB_NAMEを設定します。
    3. AZURE_STORAGE_ACCOUNT_NAMEを設定します。

サンプルをもう一度実行します。 Event Hubs 統合を有効にすると、エンコーダーがライブ イベントに接続して切断したときにイベントがログに記録されます。 その他のさまざまなイベントもログに記録されます。

サンプルを実行した後、Event Hubs とストレージ アカウントが不要になった場合は削除します。

Media Services アカウント内のリソースをクリーンアップする

ストリーミング イベントが完了し、以前にプロビジョニングされたリソースをクリーンアップする場合は、次の手順を使用します。

  1. エンコーダーからのストリーミングを停止します。
  2. ライブ イベントを停止します。 ライブ イベントが停止した後は、いかなる課金も発生しません。 もう一度開始する必要がある場合は、エンコーダーを再構成する必要がないように、同じ取り込み URL を使用できます。
  3. ライブ イベントのアーカイブをオンデマンド ストリームとして提供し続ける場合を除き、ストリーミング エンドポイントを停止します。 ライブ イベントが停止状態の場合は、料金は発生しません。
if (liveOutput != null)
{
    Console.Write("Deleting the Live Output...".PadRight(60));
    await liveOutput.DeleteAsync(WaitUntil.Completed);
    Console.WriteLine("Done");
}

if (liveEvent?.Data.ResourceState == LiveEventResourceState.Running)
{
    Console.Write("Stopping the Live Event...".PadRight(60));
    await liveEvent.StopAsync(WaitUntil.Completed, new LiveEventActionContent() { RemoveOutputsOnStop = true });
    Console.WriteLine("Done");
}

if (liveEvent != null)
{
    Console.Write("Deleting the Live Event...".PadRight(60));
    await liveEvent.DeleteAsync(WaitUntil.Completed);
    Console.WriteLine("Done");
}

if (streamingLocator != null)
{
    Console.Write("Deleting the Streaming Locator...".PadRight(60));
    await streamingLocator.DeleteAsync(WaitUntil.Completed);
    Console.WriteLine("Done");
}

if (asset != null)
{
    Console.Write("Deleting the Asset...".PadRight(60));
    await asset.DeleteAsync(WaitUntil.Completed);
    Console.WriteLine("Done");
}

残りのリソースをクリーンアップする

このチュートリアルで作成した Media Services とストレージ アカウントが不要になった場合は、前に作成したリソース グループを削除します。

次の CLI コマンドを実行します。


az group delete --name amsResourceGroup

ヘルプとサポート

Media Services に質問がある場合は、次のいずれかの方法で更新プログラムに従ってください。

  • Q & A
  • Stack Overflow。 質問に タグを付け、 を使用します azure-media-services
  • @MSFTAzureMedia するか 、@AzureSupport を使用してサポートを要求します。
  • Azure portalからサポート チケットを開きます。