이 항목은 아직 평가되지 않았습니다.- 이 항목 평가

.NET용 Media Services SDK를 사용하여 자산 배달

이 항목은 제목이 .NET용 Media Services SDK를 사용하여 응용 프로그램 작성인 Windows Azure Media Services 시리즈의 일부로, 이전에 Media Services에 추가했던 미디어 자산을 배달하는 방법을 보여 줍니다. Media Services 콘텐츠는 여러 가지 응용 프로그램 시나리오에서 배달할 수 있습니다. 미디어 자산을 다운로드하거나 로케이터 URL을 사용하여 자산에 액세스할 수 있습니다. 이러한 내용은 이 항목에서 배달 시나리오로 설명되어 있습니다. 미디어 콘텐츠는 다른 응용 프로그램이나 다른 콘텐츠 공급자에게 보낼 수 있습니다. 성능 및 확장성 향상을 위해, Azure CDN과 같은 CDN(콘텐츠 배달 네트워크)을 사용하여 콘텐츠를 배달할 수도 있습니다. 배달할 콘텐츠에는 .NET용 Media Services SDK를 사용하여 자산 수집 항목에서 설명된 대로 단순히 Media Services에 저장된 미디어 자산이 포함될 수 있습니다. 또는 .NET용 Media Services SDK를 사용하여 자산 처리 항목에서 설명된 대로 여러 가지 방식으로 처리되거나 인코딩된 미디어 자산도 해당될 수 있습니다. 현재 Media Services 릴리스의 경우 콘텐츠 배달 방식으로는 다운로드하는 방식과 서버나 Windows Azure CDN에서 주문형 자산이나 스트리밍 자산에 직접 액세스할 수 있는 다양한 로케이터 URL을 제공하는 방식이 있습니다. 라이브 스트리밍 콘텐츠가 배달 방식으로 제공될 향후 릴리스에 대한 자세한 내용은 Media Services 포럼 스레드 Media Services 기능 상태: 향후 릴리스를 참조하십시오.

이 항목에서는 다음과 같은 Media Services 콘텐츠 배달 태스크를 수행하는 방법을 보여 줍니다.

note참고
미디어 자산을 처리하려면 먼저, Media Services SDK를 사용하여 Media Services에 연결 항목에서 설명된 바와 같이 Media Services 서버 컨텍스트에 대한 참조가 있어야 합니다. 컨텍스트 개체는 다음에 나오는 코드 예제에서 _context라는 변수로 표현됩니다.

미디어 자산 다운로드

이 섹션의 코드 예제에서는 Media Services에서 미디어 자산을 다운로드하는 방법을 보여 줍니다. Assets 컬렉션으로 제공되는 자산 즉, 저장되어 있는 모든 자산을 다운로드할 수 있습니다. 또 다른 다운로드 시나리오는 작업을 실행한 결과로 생성된 미디어 자산이 하나 이상 포함되어 있는 OutputMediaAssets 컬렉션으로부터 자산을 다운로드하는 것입니다. 다음의 코드 예제에서는 작업을 통한 출력 미디어 자산을 다운로드하는 방법을 보여 줍니다. 이 방법은 다른 자산을 다운로드하는 데 적용할 수도 있습니다. 12시간 이내 완료되지 않은 다운로드는 실패하게 됩니다.

다음 코드 예제는 작업 실행 결과에 해당하는 출력 자산을 다운로드하는 방법을 보여 줍니다. 이 코드에서는 OutputMediaAssets 컬렉션의 첫 번째 자산만 다운로드합니다. 하지만 컬렉션에 여러 자산이 있을 경우 이 컬렉션에 대해 반복 실행하여 여러 자산을 다운로드할 수 있습니다. 각 자산에 대해, 코드가 AssetFiles 컬렉션에서 반복되어 개별 파일을 다운로드합니다.

note참고
이 예제에서는 .NET용 Media Services SDK를 사용하여 자산 관리 항목에 설명된 대로 작업 참조를 가져오기 위한 GetJob 메서드도 호출합니다.

static IAsset DownloadAssetToLocal(string jobId, string outputFolder)
{
    // This method illustrates how to download a single asset. 
    // However, you can iterate through the OutputAssets
    // collection, and download all assets if there are many. 

    // Get a reference to the job. 
    IJob job = GetJob(jobId);
    // Get a reference to the first output asset. If there were multiple 
    // output media assets you could iterate and handle each one.
    IAsset outputAsset = job.OutputMediaAssets[0];

    IAccessPolicy accessPolicy = _context.AccessPolicies.Create("File Download Policy", TimeSpan.FromDays(30), AccessPermissions.Read);
    ILocator locator = _context.Locators.CreateLocator(LocatorType.Sas, outputAsset, accessPolicy);

    BlobTransferClient blobTransfer = new BlobTransferClient
    {
        NumberOfConcurrentTransfers = 10,
        ParallelTransferThreadCount = 10
    };

    var downloadTasks = new List<Task>();
    foreach (IAssetFile outputFile in outputAsset.AssetFiles)
    {
        // Use the following event handler to check download progress.
        outputFile.DownloadProgressChanged += DownloadProgress;
        string localDownloadPath = Path.Combine(outputFolder, outputFile.Name);
        Console.WriteLine("File download path:  " + localDownloadPath);
        downloadTasks.Add(outputFile.DownloadAsync(Path.GetFullPath(localDownloadPath), blobTransfer, locator, CancellationToken.None));
    }

    Task.WaitAll(downloadTasks.ToArray());

    return outputAsset;
}

static void DownloadProgress(object sender, DownloadProgressChangedEventArgs e)
{
    Console.WriteLine(string.Format("Asset File:{0}  {1}% download progress. ", ((IAssetFile)sender).Name, e.Progress));
} 

주문형 콘텐츠에 대한 SAS 로케이터 만들기

Media Services에 있는 주문형 자산에 액세스하는 또 다른 방법은 서버의 자산에 연결되는 URL을 만드는 것입니다. 이러한 URL을 로케이터라고 합니다. Media Services의 로케이터는 자산에 액세스하기 위한 시간 기반의 권한과도 연관됩니다(예: 읽기, 쓰기 및 나열 권한). 주문형 미디어 자산에 직접 액세스하도록 만든 로케이터를 SAS(공유 액세스 서명) 로케이터라고 합니다. 각 자산에는 Locators 속성을 사용하여 액세스할 수 있는 ILocator 개체 컬렉션이 있습니다.

note참고
이 항목에 설명된 메서드를 사용하여 미디어 콘텐츠의 로케이터를 만들 때, Azure 저장소에서의 저장 및 전파 프로세스로 인해 30초간 지연될 수 있습니다.

다음의 코드 예제에서는 작업에 의해 생성된 출력 자산의 SAS 로케이터를 만들기 위한 필수 단계를 보여 줍니다. 이 예제에서는 작업을 실행하고 OutputMediaAssets 컬렉션에 액세스하여 코드 예제에서 참조되는 outputAsset 변수에 대한 참조를 얻은 것으로 간주합니다. 출력 자산에 대한 SAS 로케이터를 생성하는 이 코드를 실행하고 나면 결과로 생성된 URL을 사용하여 Media Services에서 파일에 직접 액세스할 수 있습니다. 이 코드가 작업에 통합되어 있는 실행 가능한 전체 코드 예제는 이 항목의 초반에 나온 Visual Studio 코드 예제 프로젝트를 참조하십시오.

이 코드 예제에서는 SAS 로케이터를 만들기 위한 다음과 같은 몇 가지 필수 단계를 수행합니다.

  • 액세스 정책을 정의합니다. 이 정책을 통해 자산 액세스 기간과 권한 유형이 결정됩니다.

  • CreateLocator 메서드 호출(var locator = _context.Locators.CreateLocator(LocatorType.Sas, asset, accessPolicy);)을 통해 SAS 로케이터를 만듭니다. 기존 자산(예: 작업의 출력 자산), 액세스 정책 및 시작 시간을 메서드에 전달합니다.

    note참고
    CreateLocator 메서드에서 반환된 URL은 자산 파일에 대한 전체 URL이 아닌 자산의 기본 경로입니다. 자산의 특정 파일에 대한 전체 URL을 구성하려면 다음 단계를 완료해야 합니다.

  • 자산의 특정 파일에 대한 URL을 만듭니다. 즉, 자산의 특정 파일에 대한 파일 이름을 로케이터 Path 속성에 추가합니다.

static void BuildAndSaveAssetSasUrlList(IAsset outputAsset)
{
    // Declare an access policy for permissions on the asset. 
    // You can call an async or sync create method. 
    IAccessPolicy policy =
        _context.AccessPolicies.Create("My 30 day readonly policy",
            TimeSpan.FromDays(30),
            AccessPermissions.Read);

    // Create a SAS locator to enable direct access to the asset 
    // in blob storage. You can call a sync or async create method.  
    // You can set the optional startTime param as 5 minutes 
    // earlier than Now to compensate for differences in time  
    // between the client and server clocks. 
    ILocator locator = _context.Locators.CreateLocator(LocatorType.Sas, outputAsset,
        policy,
        DateTime.UtcNow.AddMinutes(-5));


    // Declare a list to contain all the SAS URLs.
    List<String> fileSasUrlList = new List<String>();

    string outFilePath = Path.GetFullPath(_outputFilesFolder + @"\" + "FileSasUrlList.txt");

    // If the asset has files, build a list of URLs to 
    // each file in the asset and return. 
    foreach (IAssetFile file in outputAsset.AssetFiles)
    {
        string sasUrl = BuildFileSasUrl(file, locator);
        fileSasUrlList.Add(sasUrl);

        Console.WriteLine(sasUrl);

        // Write the URL list to a local file. You can use the saved 
        // SAS URLs to browse directly to the files in the asset.
        WriteToFile(outFilePath, sasUrl);
    }
}

static string BuildFileSasUrl(IAssetFile file, ILocator locator)
{
    // Take the locator path, add the file name, and build 
    // a full SAS URL to access this file. This is the only 
    // code required to build the full URL.
    var uriBuilder = new UriBuilder(locator.Path);
    uriBuilder.Path = uriBuilder.Path + "/" + file.Name;
            
    // Optional:  print the locator.Path to the asset, and 
    // the full SAS URL to the file
    Console.WriteLine("Locator path: ");
    Console.WriteLine(locator.Path);
    Console.WriteLine();
    Console.WriteLine("Full URL to file: ");
    Console.WriteLine(uriBuilder.Uri.AbsoluteUri);
    Console.WriteLine();


    //Return the SAS URL.
    return uriBuilder.Uri.AbsoluteUri;
}

static void WriteToFile(string outFilePath, string fileContent)
{
    StreamWriter sr = File.CreateText(outFilePath);
    sr.WriteLine(fileContent);
    sr.Close();
}

부드러운 스트리밍 또는 HLS 콘텐츠에 대한 원본 로케이터 만들기

Media Services에는 스트리밍 미디어 콘텐츠에 직접 액세스할 수 있는 방법도 있습니다. 원본 서버의 부드러운 스트리밍이나 Apple HLS(HTTP 라이브 스트리밍) 콘텐츠에 직접 액세스할 수 있는 원본 로케이터를 만들면 됩니다. SAS 로케이터 예제와 마찬가지로, 로케이터를 만들고 특정 파일에 대한 URL을 구성한 다음 콘텐츠에 액세스할 수 있습니다. 원본 로케이터를 사용하여, 자산의 스트리밍 매니페스트 파일(.ism 확장명 사용)에 대한 전체 URL을 만듭니다. 그런 다음 스트리밍 콘텐츠를 재생할 수 있는 클라이언트 응용 프로그램(예: Microsoft Silverlight)에 URL을 제공합니다.

note참고
이 항목에 설명된 메서드를 사용하여 미디어 콘텐츠의 로케이터를 만들 때, Azure 저장소에서의 저장 및 전파 프로세스로 인해 30초간 지연될 수 있습니다.

다음의 코드 예제에서는 작업에 의해 생성된 출력 자산의 원본 로케이터를 만들기 위한 필수 단계를 보여 줍니다. 이 예제에서는 부드러운 스트리밍 파일이 포함된 자산에 대한 참조와 이 코드에서 참조되는 assetToStream 변수에 대한 참조를 이미 얻을 것으로 간주합니다. 자산에 대한 원본 로케이터를 생성하는 이 코드를 실행하고 나면 결과로 생성된 URL을 사용하여 스트리밍 클라이언트 플레이어(예: Silverlight)에서 스트리밍 콘텐츠를 직접 재생할 수 있습니다.

이 코드 예제에서는 원본 로케이터를 만들기 위한 다음과 같은 몇 가지 필수 단계를 수행합니다.

  • 자산의 스트리밍 매니페스트 파일에 대한 참조를 가져옵니다. 이 파일의 확장명은 .ism입니다.

  • 액세스 정책을 정의합니다. 이 정책을 통해 자산 액세스 기간과 권한 유형이 결정됩니다.

  • CreateLocator 메서드 호출(var originLocator = _context.Locators.CreateLocator(LocatorType.OnDemandOrigin, assetToStream, policy, DateTime.UtcNow.AddMinutes(-5)))을 통해 원본 로케이터를 만듭니다. 스트리밍 미디어 파일이 포함된 기존 자산, 액세스 정책 및 시작 시간을 메서드에 전달해야 합니다.

    note참고
    CreateLocator 메서드에서 반환된 URL은 자산에 대한 기본 경로일 뿐입니다. 스트리밍 매니페스트 파일에 대한 전체 URL을 구성하려면 다음 단계를 완료해야 합니다.

  • 매니페스트 파일에 대한 URL을 만듭니다. 로케이터 Path 값과 매니페스트 파일 이름을 연결한 다음 적절한 형식을 원본 로케이터 경로에 추가합니다. 부드러운 스트리밍 형식이 필요한 클라이언트의 경우에는 file.ism/Manifest 문자열을 로케이터 경로에 추가합니다. HLS가 필요한 클라이언트라면 file.ism/Manifest(format=m3u8-aapl) 문자열을 추가합니다.

note참고
부드러운 스트리밍 콘텐츠를 가리키는 원본 로케이터 URL을 테스트하려면 코드 예제에서 만들어진 매니페스트 파일의 URL을 복사합니다. IIS 부드러운 스트리밍 시작 항목의 하위 섹션인 샘플 클라이언트 설치에 설명된 대로 간단한 Silverlight 재생 클라이언트를 만듭니다. 원본 로케이터 URL을 사용하여 스트리밍 미디어 콘텐츠를 재생하는 경우에는 이 항목의 나머지 부분에서 설명된 IIS Media Services 설치 과정이 필요 없습니다. 항목의 지침에 따라, 샘플 클라이언트를 다운로드하고 스트리밍 콘텐츠가 재생될 Silverlight를 호스팅하는 간단한 HTML 페이지를 만듭니다. 그리고, 샘플에서 만든 원본 로케이터 URL을 HTML 페이지 MediaUrl 특성에 붙여 넣은 다음 스트리밍 콘텐츠를 재생할 브라우저에서 해당 페이지를 로드합니다.

note참고
HLS 콘텐츠를 가리키는 원본 로케이터 URL을 테스트하려면 코드 예제에서 만들어진 매니페스트 파일의 URL을 복사합니다. 이 URL이 추가될 iOS 장치가 없는 경우에는 Safari 브라우저에서 스트리밍 콘텐츠를 재생할 수 있는 간단한 HTML 페이지를 만들 수 있습니다. 이 작업은 IIS Media Services를 사용한 Apple HTTP 라이브 스트리밍 항목의 하위 섹션인 "Safari에서 사용할 HTML 5 페이지 만들기"를 참조하십시오.

public enum MediaContentType
{
    SmoothStreaming,
    HLS
}
public static ILocator GetStreamingOriginLocator(string targetAssetID, MediaContentType contentType)
{
    // Get a reference to the asset you want to stream.
    IAsset assetToStream = GetAsset(targetAssetID);

    // Get a reference to the streaming manifest file from the  
    // collection of files in the asset. 
    var theManifest =
                        from f in assetToStream.AssetFiles
                        where f.Name.EndsWith(".ism")
                        select f;

    // Cast the reference to a true IAssetFile type. 
    IAssetFile manifestFile = theManifest.First();
            
    // Create a 30-day readonly access policy. 
    IAccessPolicy policy = _context.AccessPolicies.Create("Streaming policy",
        TimeSpan.FromDays(30),
        AccessPermissions.Read);

    // Create a locator to the streaming content on an origin. 
    ILocator originLocator = _context.Locators.CreateLocator(LocatorType.OnDemandOrigin, assetToStream,
        policy,
        DateTime.UtcNow.AddMinutes(-5));
            
    // Display some useful values based on the locator.
    // Display the base path to the streaming asset on the origin server.
    Console.WriteLine("Streaming asset base path on origin: ");
    Console.WriteLine(originLocator.Path);
    Console.WriteLine();

    // Create a full URL to the manifest file. Use this for playback
    // in smooth streaming and HLS media clients. 
    string urlForClientStreaming = originLocator.Path + manifestFile.Name + "/manifest";
    if (contentType == MediaContentType.HLS)
        urlForClientStreaming = String.Format("{0}{1}", urlForClientStreaming, "(format=m3u8-aapl)"); 

    Console.WriteLine("URL to manifest for client streaming: ");
    Console.WriteLine(urlForClientStreaming);
    Console.WriteLine();

    // Display the ID of the origin locator, the access policy, and the asset.
    Console.WriteLine("Origin locator Id: " + originLocator.Id);
    Console.WriteLine("Access policy Id: " + policy.Id);
    Console.WriteLine("Streaming asset Id: " + assetToStream.Id);

    // For convenience, write the URL to a local file. Use the saved 
    // streaming URL to browse directly to the asset in a smooth streaming client.  
    string outFilePath = Path.GetFullPath(_outputFilesFolder + @"\" + "StreamingUrl.txt");
    WriteToFile(outFilePath, urlForClientStreaming);


    // Return the locator. 
    return originLocator;
}
 

참고 항목


빌드 날짜:

2013-04-11
이 정보가 도움이 되었습니까?
(1500자 남음)

커뮤니티 추가 항목

추가
© 2013 Microsoft. All rights reserved.
facebook page visit twitter rss feed newsletter