匯出 (0) 列印
全部展開

使用 Media Services SDK for .NET 大量擷取資產

更新日期: 2014年8月

上傳大型資產檔案是資產建立的瓶頸。大量擷取資產或「大量擷取」牽涉到將資產建立與上傳程序分離。若要使用大量擷取方法,請建立描述資產及其相關檔案的資訊清單 (IngestManifest)。接著,使用您選擇上傳的方法上傳相關檔案到資訊清單的 Blob 容器。Microsoft Azure Media Services 會監控與資訊清單相關連的 Blob 容器。檔案上傳至 Blob 容器之後,Microsoft Azure Media Services 會根據資訊清單中之資產的設定完成資產建立 (IngestManifestAsset)。

本主題說明使用 Microsoft Azure Media Services SDK for .NET 大量擷取資產。如需使用 REST API 大量擷取資產的相關資訊,請參閱使用 REST API 大量擷取資產

note附註
媒體服務在建置串流內容的 URL 時使用 IAssetFile.Name 屬性值 (例如,http://{WAMSAccount}.origin.mediaservices.windows.net/{GUID}/{IAssetFile.Name}/streamingParameters)。因此,不允許百分比編碼。名稱屬性的值沒有以下任何保留的百分比編碼字元:!*'();:@&=+$,/?%#[]"。檔案副檔名只能有一個 ‘.’。

Important重要事項
如果尚未下載及設定此專案,請參閱Building Applications with the Media Services SDK for .NET簡介主題中的指示。本主題中的每個程式碼範例,皆是使用已下載專案當中的一或多個方法進行說明 (專案的方案檔案為 MediaServicesSDKSamples.sln)。若要尋找特定範例的程式碼,請在已下載的專案中搜尋範例方法的名稱。若要執行特定的程式碼範例,請使用必要參數來呼叫相關方法。

大量擷取的基本工作流程將於下列幾節中討論:

note附註
使用 Microsoft Azure Media Services SDK 開發應用程式時,必須先有 媒體服務 伺服器內容的參考,如「透過 Media Services SDK for .NET 連線至媒體服務」主題所述。內容物件在下列程式碼範例中以名為 context 的變數代表。

IngestManifest 代表要透過大量擷取建立的一組資產,以及其相關的資產檔案。若要建立新的 IngestManifest,請在伺服器內容上呼叫 IngestManifests 集合公開的 Create 方法。此方法會使用您提供的資訊清單名稱,建立新的 IngestManifest

程式碼範例>一節中本主題結尾處有提供完整的程式碼範例。

IIngestManifest manifest = context.IngestManifests.Create(name);

建立將與大量 IngestManifest 產生關聯的資產。系統會使用伺服器內容上的 Assets 集合,來建立這些資產。設定大量擷取的資產加密選項。

程式碼範例>一節中本主題結尾處有提供完整的程式碼範例。

// Create the assets that will be associated with this bulk ingest manifest
IAsset destAsset1 = _context.Assets.Create(name + "_asset_1", AssetCreationOptions.None);
IAsset destAsset2 = _context.Assets.Create(name + "_asset_2", AssetCreationOptions.None);

IngestManifestAsset 會將 Asset 與大量 IngestManifest 產生關聯,以進行大量擷取。其亦會建立構成每個AssetAssetFiles的關聯。若要建立 IngestManifestAsset,請在伺服器內容上使用 Create 方法。

下列範例示範建立兩個新的 IngestManifestAssets,其會將先前建立的兩個資產與大量擷取資訊清單產生關聯。每個 IngestManifestAsset 亦會針對執行大量擷取時為每個資產上傳的一組檔案,建立其關聯。檔案路徑屬於 MediaServiceSDKSamples 專案的一部分。

程式碼範例>一節中本主題結尾處有提供完整的程式碼範例。


string filename1 = _singleInputMp4Path;
string filename2 = _primaryFilePath;
string filename3 = _singleInputFilePath;

IIngestManifestAsset bulkAsset1 =  manifest.IngestManifestAssets.Create(destAsset1, new[] { filename1 });
IIngestManifestAsset bulkAsset2 =  manifest.IngestManifestAssets.Create(destAsset2, new[] { filename2, filename3 });

您可使用任何適當的高速用戶端應用程式,應用程式必須能夠將資產檔案上傳至 IngestManifestBlobStorageUriForUpload 屬性提供的 Blob 儲存容器 URI。Aspera On Demand for Azure Application 就是著名的高速上傳服務。您也可以寫入程式碼來上傳資產檔案,如下列程式碼範例所示。

static void UploadBlobFile(string destBlobURI, string filename)
{
    Task copytask = new Task(() =>
    {
        var storageaccount = new CloudStorageAccount(new StorageCredentials(_storageAccountName, _storageAccountKey), true);
        CloudBlobClient blobClient = storageaccount.CreateCloudBlobClient();
        CloudBlobContainer blobContainer = blobClient.GetContainerReference(destBlobURI);

        string[] splitfilename = filename.Split('\\');
        var blob = blobContainer.GetBlockBlobReference(splitfilename[splitfilename.Length - 1]);

        using (var stream = System.IO.File.OpenRead(filename))
            blob.UploadFromStream(stream);

        lock (consoleWriteLock)
        {
            Console.WriteLine("Upload for {0} completed.", filename);
        }
    });

    copytask.Start();
}

在下列程式碼範例中,會顯示本主題所用的上傳資產檔案程式碼範例。


UploadBlobFile(manifest.BlobStorageUriForUpload, filename1);
UploadBlobFile(manifest.BlobStorageUriForUpload, filename2);
UploadBlobFile(manifest.BlobStorageUriForUpload, filename3);

您可輪詢 IngestManifestStatistics 屬性,以判斷與 IngestManifest 相關之所有資產的大量擷取進度。每次輪詢 Statistics 屬性時皆必須使用新的伺服器內容,以獲得最新的進度資訊。

下列範例示範使用 IngestManifest 的 Id 來輪詢 IngestManifest

程式碼範例>一節中本主題結尾處有提供完整的程式碼範例。

static void MonitorBulkManifest(string manifestID)
{
   bool bContinue = true;
   while (bContinue)
   {
      CloudMediaContext context = GetContext();
      IIngestManifest manifest = context.IngestManifests.Where(m => m.Id == manifestID).FirstOrDefault();

      if (manifest != null)
      {
         lock(consoleWriteLock)
         {
            Console.WriteLine("\nWaiting on all file uploads.");
            Console.WriteLine("PendingFilesCount  : {0}", manifest.Statistics.PendingFilesCount);
            Console.WriteLine("FinishedFilesCount : {0}", manifest.Statistics.FinishedFilesCount);
            Console.WriteLine("{0}% complete.\n", (float)manifest.Statistics.FinishedFilesCount / (float)(manifest.Statistics.FinishedFilesCount + manifest.Statistics.PendingFilesCount) * 100);

            if (manifest.Statistics.PendingFilesCount == 0)
            {
               Console.WriteLine("Completed\n");
               bContinue = false;
            }
         }

         if (manifest.Statistics.FinishedFilesCount < manifest.Statistics.PendingFilesCount)
            Thread.Sleep(60000);
      }
      else //=== Manifest is null ===//
         bContinue = false;
   }
}

下列範例程式碼是由 MediaServicesSDKSample 專案中衍生出來的,可以在這裡下載:Building Applications with the Media Services SDK for .NET.

using System;
using System.Configuration;
using System.Globalization;
using System.IO;
using System.Net;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Xml;
using System.Linq;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.MediaServices.Client;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using Microsoft.WindowsAzure.Storage.Auth;
using System.Collections.Generic;
using System.Reflection;

namespace Microsoft.Samples.WindowsAzureMediaServicesSDK.BulkIngest
{
    class Program
    {
        private static CloudMediaContext _context = null;
        private static readonly string _supportFiles = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + @"\..\..\supportFiles";
        private static readonly string _singleInputFilePath =
            Path.GetFullPath(_supportFiles + @"\multifile\interview2.wmv");
        private static readonly string _singleInputMp4Path =
            Path.GetFullPath(_supportFiles + @"\multifile\BigBuckBunny.mp4");
        private static readonly string _primaryFilePath =
            Path.GetFullPath(_supportFiles + @"\multifile\interview1.wmv");

        private static System.Object consoleWriteLock = new Object();

        private static readonly string _accountName =
            ConfigurationManager.AppSettings["MediaServicesAccountName"];
        private static readonly string _accountKey =
            ConfigurationManager.AppSettings["MediaServicesAccountKey"];

        // Media Services storage account credentials.
        private static readonly string _storageAccountName =
            ConfigurationManager.AppSettings["MediaServicesStorageAccountName"];
        private static readonly string _storageAccountKey =
            ConfigurationManager.AppSettings["MediaServicesStorageAccountKey"];

        static void Main(string[] args)
        {
            _context = GetContext();
            string manifestName = "TestManifest";

            CreateBulkIngestManifest(manifestName);
            ListIngestManifests();
            DeleteBulkManifest(manifestName);
        }


        static CloudMediaContext GetContext()
        {
            return new CloudMediaContext(_accountName, _accountKey);
        }

        static IIngestManifest CreateBulkIngestManifest(string name)
        {
            Console.WriteLine("\n===============================================");
            Console.WriteLine("========[ CREATE BULK INGEST MANIFEST ]========");
            Console.WriteLine("===============================================\n");


            IIngestManifest manifest = _context.IngestManifests.Create(name);

            IAsset destAsset1 = _context.Assets.Create(name + "_asset_1", AssetCreationOptions.None);
            IAsset destAsset2 = _context.Assets.Create(name + "_asset_2", AssetCreationOptions.None);

            string filename1 = _singleInputMp4Path;
            string filename2 = _primaryFilePath;
            string filename3 = _singleInputFilePath;

            //=== Preently, each asset filename uploaded must be unique for an individual Bulk ingest manifest. So two assets can not have ===//
            //=== the same asset filename or an exception will be thrown for duplicate filename.                                           ===//
            IIngestManifestAsset bulkAsset1 = manifest.IngestManifestAssets.Create(destAsset1, new[] { filename1 });
            IIngestManifestAsset bulkAsset2 = manifest.IngestManifestAssets.Create(destAsset2, new[] { filename2, filename3 });

            ListIngestManifests(manifest.Id);

            Console.WriteLine("\n===============================================");
            Console.WriteLine("===[ BULK INGEST MANIFEST MONITOR FILE COPY]===");
            Console.WriteLine("===============================================\n");

            UploadBlobFile(manifest.BlobStorageUriForUpload, filename1);
            UploadBlobFile(manifest.BlobStorageUriForUpload, filename2);
            UploadBlobFile(manifest.BlobStorageUriForUpload, filename3);

            MonitorBulkManifest(manifest.Id);
            ListIngestManifests(manifest.Id);

            return manifest;
        }


        // Upload a file into Blob Storage
        static void UploadBlobFile(string destBlobURI, string filename)
        {
            Task copytask = new Task(() =>
            {
                var storageaccount = new CloudStorageAccount(new StorageCredentials(_storageAccountName, _storageAccountKey), true);
                CloudBlobClient blobClient = storageaccount.CreateCloudBlobClient();
                CloudBlobContainer blobContainer = blobClient.GetContainerReference(destBlobURI);

                string[] splitfilename = filename.Split('\\');
                var blob = blobContainer.GetBlockBlobReference(splitfilename[splitfilename.Length - 1]);

                using (var stream = System.IO.File.OpenRead(filename))
                    blob.UploadFromStream(stream);

                lock (consoleWriteLock)
                {
                    Console.WriteLine("Upload for {0} completed.", filename);
                }
            });

            copytask.Start();
        }

        static void DeleteBulkManifest(string name)
        {
            Console.WriteLine("\n===============================================");
            Console.WriteLine("=======[ DELETE BULK INGEST MANIFESTS ]========");
            Console.WriteLine("===============================================\n");

            var manifest = _context.IngestManifests.Where(c => c.Name == name).FirstOrDefault();
            DeleteBulkManifestAssets(manifest.Id);

            Console.WriteLine("Deleting Manifest...\n\tName : {0}\n\tManifest ID : {1}...", manifest.Name, manifest.Id);
            manifest.Delete();
            Console.WriteLine("Delete Complete.\n");
        }

        static void DeleteBulkManifestAssets(string manifestID)
        {
            Console.WriteLine("\n===============================================");
            Console.WriteLine("=====[ DELETE BULK INGEST MANIFEST ASSETS ]====");
            Console.WriteLine("===============================================\n");

            foreach (IIngestManifest manifest in _context.IngestManifests.Where(c => c.Id == manifestID))
            {
                Console.WriteLine("Deleting assets for manifest named : {0}...\n", manifest.Name);
                foreach (IIngestManifestAsset manifestAsset in manifest.IngestManifestAssets)
                {
                    foreach (ILocator locator in manifestAsset.Asset.Locators)
                    {
                        Console.WriteLine("Deleting locator {0} for asset {1}", locator.Path, manifestAsset.Asset.Id);
                        locator.Delete();
                    }
                    Console.WriteLine("Deleting asset {0}\n", manifestAsset.Asset.Id);
                    manifestAsset.Asset.Delete();
                }
            }
        }

        static void MonitorBulkManifest(string manifestID)
        {
            bool bContinue = true;
            while (bContinue)
            {
                //=== We need a new context here because IIngestManifestStatistics is considered an expensive ===//
                //=== property and not updated realtime for a context.                                        ===//
                CloudMediaContext context = GetContext();

                IIngestManifest manifest = context.IngestManifests.Where(m => m.Id == manifestID).FirstOrDefault();

                if (manifest != null)
                {
                    lock (consoleWriteLock)
                    {
                        Console.WriteLine("\nWaiting on all file uploads.");
                        Console.WriteLine("PendingFilesCount  : {0}", manifest.Statistics.PendingFilesCount);
                        Console.WriteLine("FinishedFilesCount : {0}", manifest.Statistics.FinishedFilesCount);
                        Console.WriteLine("{0}% complete.\n", (float)manifest.Statistics.FinishedFilesCount / (float)(manifest.Statistics.FinishedFilesCount + manifest.Statistics.PendingFilesCount) * 100);


                        if (manifest.Statistics.PendingFilesCount == 0)
                        {
                            Console.WriteLine("Completed\n");
                            bContinue = false;
                        }
                    }

                    if (manifest.Statistics.FinishedFilesCount < manifest.Statistics.PendingFilesCount)
                    {
                        Thread.Sleep(60000);
                    }
                }
                else //=== Manifest is null ===//
                    bContinue = false;
            }
        }

        static IQueryable<IIngestManifest> ListIngestManifests(string manifestId = "")
        {
            CloudMediaContext context = GetContext();

            Console.WriteLine("\n===============================================");
            Console.WriteLine("===========[ BULK INGEST MANIFESTS ]===========");
            Console.WriteLine("===============================================\n");

            IQueryable<IIngestManifest> manifests = null;

            //=== If an Id is supplied, list the manifest with that Id. Otherwise, list all manifests ===//
            if (manifestId == "")
                manifests = context.IngestManifests;
            else
                manifests = context.IngestManifests.Where(m => m.Id == manifestId);

            foreach (IIngestManifest manifest in manifests)
            {
                Console.WriteLine("Manifest Name  : {0}", manifest.Name);
                Console.WriteLine("Manifest State : {0}", manifest.State.ToString());
                Console.WriteLine("Manifest Id    : {0}", manifest.Id);
                Console.WriteLine("Manifest Last Modified      : {0}", manifest.LastModified.ToLocalTime().ToString());
                Console.WriteLine("Manifest PendingFilesCount  : {0}", manifest.Statistics.PendingFilesCount);
                Console.WriteLine("Manifest FinishedFilesCount : {0}", manifest.Statistics.FinishedFilesCount);
                Console.WriteLine("Manifest BLOB URI : {0}\n", manifest.BlobStorageUriForUpload);

                foreach (IIngestManifestAsset manifestasset in manifest.IngestManifestAssets)
                {
                    Console.WriteLine("\tAsset Name    : {0}", manifestasset.Asset.Name);
                    Console.WriteLine("\tAsset ID      : {0}", manifestasset.Asset.Id);
                    Console.WriteLine("\tAsset Options : {0}", manifestasset.Asset.Options.ToString());
                    Console.WriteLine("\tAsset State   : {0}", manifestasset.Asset.State.ToString());
                    Console.WriteLine("\tAsset Files....");

                    foreach (IIngestManifestFile assetfile in manifestasset.IngestManifestFiles)
                    {
                        Console.WriteLine("\t\t{0}\n\t\tFile State : {1}\n", assetfile.Name, assetfile.State.ToString());
                    }
                    Console.WriteLine("");
                }
            }

            return manifests;
        }
    }
}

App.Config 檔案範例

Important重要事項
執行範例之前,您需要先新增 MediaServicesAccountName、MediaServicesAccountKey、MediaServicesStorageAccountName 以及 MediaServicesStorageAccountKey 的值。若要尋找這些值,您可前往 Azure 入口網站選取 [Azure Media Service] 帳戶,然後按一下 [管理金鑰] 圖示。針對 Azure 儲存體帳戶執行相同動作。

<?xml version="1.0"?>
<configuration>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0" />
  </startup>
  <appSettings>
    <add key="MediaServicesAccountName" value="Enter Your Azure Media Services Account Name " />
    <add key="MediaServicesAccountKey" value="Enter Your Azure Media Services Account Key " />
    <add key="MediaServicesStorageAccountName" value=" Enter the Storage Account Name used with Azure Media Services " />
    <add key="MediaServicesStorageAccountKey" value=" Enter the Storage Account Key used with Azure Media Services " />
  </appSettings>
</configuration>

範例程式碼的範例輸出。


===============================================
========[ CREATE BULK INGEST MANIFEST ]========
===============================================


===============================================
===========[ BULK INGEST MANIFESTS ]===========
===============================================

Manifest Name  : TestManifest
Manifest State : Activating
Manifest Id    : nb:mid:UUID:47e2efdf-8ec8-6143-a4ac-bf43efba35c8
Manifest Last Modified      : 2/25/2013 1:50:09 PM
Manifest PendingFilesCount  : 3
Manifest FinishedFilesCount : 0
Manifest BLOB URI : https://mediasvcm13w6rsvm521t.blob.core.windows.net/manifest
-402dcea0-411c-48f2-90fc-805c63a92a72

        Asset Name    : TestManifest_asset_2
        Asset ID      : nb:cid:UUID:0dbfcaf9-e53c-4399-99c2-ba207b1821d9
        Asset Options : None
        Asset State   : Initialized
        Asset Files....
                interview2.wmv
                File State : Pending

                interview1.wmv
                File State : Pending


        Asset Name    : TestManifest_asset_1
        Asset ID      : nb:cid:UUID:7a7188b5-d39d-42de-b3c7-f418174b14f3
        Asset Options : None
        Asset State   : Initialized
        Asset Files....
                BigBuckBunny.mp4
                File State : Pending



===============================================
===[ BULK INGEST MANIFEST MONITOR FILE COPY]===
===============================================


Waiting on all file uploads.
PendingFilesCount  : 3
FinishedFilesCount : 0
0% complete.

Upload for c:\Projects\Media Services\BulkIngestTest\supportFiles\multifile\inte
rview2.wmv completed.
Upload for c:\Projects\Media Services\BulkIngestTest\supportFiles\multifile\BigB
uckBunny.mp4 completed.
Upload for c:\Projects\Media Services\BulkIngestTest\supportFiles\multifile\inte
rview1.wmv completed.

Waiting on all file uploads.
PendingFilesCount  : 0
FinishedFilesCount : 3
100% complete.

Completed


===============================================
===========[ BULK INGEST MANIFESTS ]===========
===============================================

Manifest Name  : TestManifest
Manifest State : Inactive
Manifest Id    : nb:mid:UUID:47e2efdf-8ec8-6143-a4ac-bf43efba35c8
Manifest Last Modified      : 2/25/2013 1:50:48 PM
Manifest PendingFilesCount  : 0
Manifest FinishedFilesCount : 3
Manifest BLOB URI : https://mediasvcm13w6rsvm521t.blob.core.windows.net/manifest
-402dcea0-411c-48f2-90fc-805c63a92a72

        Asset Name    : TestManifest_asset_2
        Asset ID      : nb:cid:UUID:0dbfcaf9-e53c-4399-99c2-ba207b1821d9
        Asset Options : None
        Asset State   : Initialized
        Asset Files....
                interview2.wmv
                File State : Finished

                interview1.wmv
                File State : Finished


        Asset Name    : TestManifest_asset_1
        Asset ID      : nb:cid:UUID:7a7188b5-d39d-42de-b3c7-f418174b14f3
        Asset Options : None
        Asset State   : Initialized
        Asset Files....
                BigBuckBunny.mp4
                File State : Finished



===============================================
===========[ BULK INGEST MANIFESTS ]===========
===============================================

Manifest Name  : TestManifest
Manifest State : Inactive
Manifest Id    : nb:mid:UUID:c44efbcc-8f6a-f94a-aa21-2d0c1166ecb7
Manifest Last Modified      : 2/25/2013 1:47:47 PM
Manifest PendingFilesCount  : 0
Manifest FinishedFilesCount : 0
Manifest BLOB URI : https://mediasvcm13w6rsvm521t.blob.core.windows.net/manifest
-f001a80c-3c37-4a31-8ffc-b4bfe98b56be

        Asset Name    : TestManifest_asset_1
        Asset ID      : nb:cid:UUID:350ceed6-086a-413d-9bb9-a8a2f07a60f5
        Asset Options : None
        Asset State   : Initialized
        Asset Files....

Manifest Name  : TestManifest
Manifest State : Inactive
Manifest Id    : nb:mid:UUID:47e2efdf-8ec8-6143-a4ac-bf43efba35c8
Manifest Last Modified      : 2/25/2013 1:50:48 PM
Manifest PendingFilesCount  : 0
Manifest FinishedFilesCount : 3
Manifest BLOB URI : https://mediasvcm13w6rsvm521t.blob.core.windows.net/manifest
-402dcea0-411c-48f2-90fc-805c63a92a72

        Asset Name    : TestManifest_asset_2
        Asset ID      : nb:cid:UUID:0dbfcaf9-e53c-4399-99c2-ba207b1821d9
        Asset Options : None
        Asset State   : Initialized
        Asset Files....
                interview2.wmv
                File State : Finished

                interview1.wmv
                File State : Finished


        Asset Name    : TestManifest_asset_1
        Asset ID      : nb:cid:UUID:7a7188b5-d39d-42de-b3c7-f418174b14f3
        Asset Options : None
        Asset State   : Initialized
        Asset Files....
                BigBuckBunny.mp4
                File State : Finished



===============================================
=======[ DELETE BULK INGEST MANIFESTS ]========
===============================================


===============================================
=====[ DELETE BULK INGEST MANIFEST ASSETS ]====
===============================================

Deleting assets for manifest named : TestManifest...

Deleting asset nb:cid:UUID:350ceed6-086a-413d-9bb9-a8a2f07a60f5

Deleting Manifest...
        Name : TestManifest
        Manifest ID : nb:mid:UUID:c44efbcc-8f6a-f94a-aa21-2d0c1166ecb7...
Delete Complete.


===============================================
=====[ DELETE BULK INGEST MANIFEST ASSETS ]====
===============================================

Deleting assets for manifest named : TestManifest...

Deleting asset nb:cid:UUID:0dbfcaf9-e53c-4399-99c2-ba207b1821d9

Deleting asset nb:cid:UUID:7a7188b5-d39d-42de-b3c7-f418174b14f3

Deleting Manifest...
        Name : TestManifest
        Manifest ID : nb:mid:UUID:47e2efdf-8ec8-6143-a4ac-bf43efba35c8...
Delete Complete.

您可隨時進行下一個主題: 靜態封裝.

另請參閱

顯示:
© 2015 Microsoft