销售电话: 1-800-867-1380

将现有的 BLOB 复制到 Media Services 资产中

更新时间: 2014年8月

本主题介绍如何将存储帐户中的 BLOB 复制到新的 Microsoft Azure Media Services 资产中。

BLOB 可以存在于与媒体服务帐户关联的存储帐户中,也可以存在于不与媒体服务帐户关联的存储帐户中。本主题演示如何将存储帐户中的 Blob 复制到 Media Services 资产中。请注意,你还可以跨数据中心复制。但是,这样做可能会产生费用。有关定价的详细信息,请参阅 Data Transfers(数据传输)。

Important重要提示
在不使用 Media Service API 的情况下,你不应该尝试更改 Media Services 生成的 BLOB 容器内容。

  • 新的或现有的 Azure 订阅中的两个 媒体服务 帐户。请参阅主题 How to Create a Media Services Account(如何创建 Media Services 帐户)。

  • 操作系统:Windows 7、Windows 2008 R2 或 Windows 8。

  • .NET Framework 4。

  • Visual Studio 2013、Visual Studio 2012 或 Visual Studio 2010 SP1(专业版、高级版、旗舰版或速成版)。

在本部分中,你将创建和设置一个 C# 控制台应用程序项目。

  1. 使用 Visual Studio 2012 或 Visual Studio 2010 SP1 创建包含 C#“控制台应用程序”项目的新解决方案。为“名称”输入 CopyExistingBlobsIntoAsset,然后单击“确定”

  2. 使用 Nuget 添加对 Media Services 相关 DLL 的引用。在 Visual Studio 主菜单中,选择“工具”->“库程序包管理器”->“程序包管理器控制台”。在控制台窗口中,键入 Install-Package windowsazure.mediaservices,然后按 Enter。

  3. 添加此项目所需的其他引用:System.Configuration.

  4. 将默认添加到 Programs.cs 文件中的 using 语句替换为以下语句:

    using System;
    using System.Linq;
    using System.Configuration;
    using System.IO;
    using System.Text;
    using System.Threading;
    using System.Threading.Tasks;
    using System.Collections.Generic;
    using Microsoft.WindowsAzure.Storage;
    using Microsoft.WindowsAzure.MediaServices.Client;
    using Microsoft.WindowsAzure;
    using System.Web;
    using Microsoft.WindowsAzure.Storage.Blob;
    using Microsoft.WindowsAzure.Storage.Auth;
    
  5. appSettings 节添加到 .config 文件,并基于 Media Services 和 Storage 密钥和名称值更新值。

    <appSettings>
      <add key="MediaServicesAccountName" value="Media-Services-Account-Name"/>
      <add key="MediaServicesAccountKey" value="Media-Services-Account-Key"/>
      <add key="MediaServicesStorageAccountName" value="Media-Services-Storage-Account-Name"/>
      <add key="MediaServicesStorageAccountKey" value="Media-Services-Storage-Account-Key"/>
      <add key="ExternalStorageAccountName" value="External-Storage-Account-Name"/>
      <add key="ExternalStorageAccountKey" value="External-Storage-Account-Key"/>
    </appSettings>
    

下面的代码示例执行以下任务:

  1. 创建 CloudMediaContext 实例。

  2. 创建 CloudStorageAccount 实例:_sourceStorageAccount 和 _destinationStorageAccount。

  3. 将本地目录中的平滑流文件上载到位于 _sourceStorageAccount 中的 Blob 容器中。

  4. 创建一个新资产。为此资产创建的 Blob 容器位于 _destinationStorageAccount 中。

  5. 使用 Windows Azure 存储 SDK 将指定的 Blob 复制到与此资产关联的容器中。

    Warning警告
    如果定位符已过期,复制操作不会引发异常。

  6. 将 .ism 文件设置为主文件。

  7. 为与此资产关联的 OnDemandOrigin 定位符创建平滑流 URL。

class Program
{
    // Read values from the App.config file. 
    static string _accountName = ConfigurationManager.AppSettings["MediaServicesAccountName"];
    static string _accountKey = ConfigurationManager.AppSettings["MediaServicesAccountKey"];
    static string _storageAccountName = ConfigurationManager.AppSettings["MediaServicesStorageAccountName"];
    static string _storageAccountKey = ConfigurationManager.AppSettings["MediaServicesStorageAccountKey"];
    static string _externalStorageAccountName = ConfigurationManager.AppSettings["ExternalStorageAccountName"];
    static string _externalStorageAccountKey = ConfigurationManager.AppSettings["ExternalStorageAccountKey"];

    private static MediaServicesCredentials _cachedCredentials = null;
    private static CloudMediaContext _context = null;

    private static CloudStorageAccount _sourceStorageAccount = null;
    private static CloudStorageAccount _destinationStorageAccount = null;

    static void Main(string[] args)
    {
        _cachedCredentials = new MediaServicesCredentials(
                        _accountName,
                        _accountKey);
        // Use the cached credentials to create CloudMediaContext.
        _context = new CloudMediaContext(_cachedCredentials);

        // In this example the storage account from which we copy blobs is not 
        // associated with the Media Services account into which we copy blobs.
        // But the same code will work for coping blobs from a storage account that is 
        // associated with the Media Services account.
        //
        // Get a reference to a storage account that is not associated with a Media Services account
        // (an external account).  
        StorageCredentials externalStorageCredentials =
            new StorageCredentials(_externalStorageAccountName, _externalStorageAccountKey);
        _sourceStorageAccount = new CloudStorageAccount(externalStorageCredentials, true);

        //Get a reference to the storage account that is associated with a Media Services account. 
        StorageCredentials mediaServicesStorageCredentials =
            new StorageCredentials(_storageAccountName, _storageAccountKey);
        _destinationStorageAccount = new CloudStorageAccount(mediaServicesStorageCredentials, false);

        // Upload Smooth Streaming files into a storage account.
        string localMediaDir = @"C:\supportFiles\streamingfiles";
        CloudBlobContainer blobContainer =
            UploadContentToStorageAccount(localMediaDir);

        // Create a new asset and copy the smooth streaming files into 
        // the container that is associated with the asset.
        IAsset asset = CreateAssetFromExistingBlobs(blobContainer);

        // Get the streaming URL for the smooth streaming files 
        // that were copied into the asset.   
        string urlForClientStreaming = CreateStreamingLocator(asset);
        Console.WriteLine("Smooth Streaming URL: " + urlForClientStreaming);

        Console.ReadLine();
    }

    /// <summary>
    /// Uploads content from a local directory into the specified storage account.
    /// In this example the storage account is not associated with the Media Services account.
    /// </summary>
    /// <param name="localPath">The path from which to upload the files.</param>
    /// <returns>The container that contains the uploaded files.</returns>
    static public CloudBlobContainer UploadContentToStorageAccount(string localPath)
    {
        CloudBlobClient externalCloudBlobClient = _sourceStorageAccount.CreateCloudBlobClient();
        CloudBlobContainer externalMediaBlobContainer =
            externalCloudBlobClient.GetContainerReference(externalCloudBlobClient.BaseUri + "streamingfiles");

        externalMediaBlobContainer.CreateIfNotExists();

        // Upload files to the blob container.  
        DirectoryInfo uploadDirectory = new DirectoryInfo(localPath);
        foreach (var file in uploadDirectory.EnumerateFiles())
        {
            CloudBlockBlob blob = externalMediaBlobContainer.GetBlockBlobReference(file.Name);

            blob.UploadFromFile(file.FullName, FileMode.Open);
        }

        return externalMediaBlobContainer;
    }

    /// <summary>
    /// Creates a new asset and copies blobs from the specifed storage account.
    /// </summary>
    /// <param name="mediaBlobContainer">The specified blob container.</param>
    /// <returns>The new asset.</returns>
    static public IAsset CreateAssetFromExistingBlobs(CloudBlobContainer mediaBlobContainer)
    {
        // Create a new asset. 
        IAsset asset = _context.Assets.Create("NewAsset_" + Guid.NewGuid(), AssetCreationOptions.None);

        IAccessPolicy writePolicy = _context.AccessPolicies.Create("writePolicy",
            TimeSpan.FromHours(24), AccessPermissions.Write);
        ILocator destinationLocator = _context.Locators.CreateLocator(LocatorType.Sas, asset, writePolicy);

        CloudBlobClient destBlobStorage = _destinationStorageAccount.CreateCloudBlobClient();

        // Get the asset container URI and Blob copy from mediaContainer to assetContainer. 
        string destinationContainerName = (new Uri(destinationLocator.Path)).Segments[1];

        CloudBlobContainer assetContainer =
            destBlobStorage.GetContainerReference(destinationContainerName);

        if (assetContainer.CreateIfNotExists())
        {
            assetContainer.SetPermissions(new BlobContainerPermissions
            {
                PublicAccess = BlobContainerPublicAccessType.Blob
            });
        }

        var blobList = mediaBlobContainer.ListBlobs();
        foreach (var sourceBlob in blobList)
        {
            var assetFile = asset.AssetFiles.Create((sourceBlob as ICloudBlob).Name);
            CopyBlob(sourceBlob as ICloudBlob, assetContainer);
        }

        destinationLocator.Delete();
        writePolicy.Delete();

        // Since we copied a set of Smooth Streaming files, 
        // set the .ism file to be the primary file. 
        SetISMFileAsPrimary(asset);

        return asset;
    }

    /// <summary>
    /// Creates the OnDemandOrigin locator in order to get the streaming URL.
    /// </summary>
    /// <param name="asset">The asset that contains the smooth streaming files.</param>
    /// <returns>The streaming URL.</returns>
    static public string CreateStreamingLocator(IAsset asset)
    {
        var ismAssetFile = asset.AssetFiles.ToList().
            Where(f => f.Name.EndsWith(".ism", StringComparison.OrdinalIgnoreCase)).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, asset,
            policy,
            DateTime.UtcNow.AddMinutes(-5));

        return originLocator.Path + ismAssetFile.Name + "/manifest";
    }

    /// <summary>
    /// Copies the specified blob into the specified container.
    /// </summary>
    /// <param name="sourceBlob">The source container.</param>
    /// <param name="destinationContainer">The destination container.</param>
    static private void CopyBlob(ICloudBlob sourceBlob, CloudBlobContainer destinationContainer)
    {
        var signature = sourceBlob.GetSharedAccessSignature(new SharedAccessBlobPolicy
        {
            Permissions = SharedAccessBlobPermissions.Read,
            SharedAccessExpiryTime = DateTime.UtcNow.AddHours(24)
        });

        ICloudBlob destinationBlob = destinationContainer.GetBlockBlobReference(sourceBlob.Name);

        if (destinationBlob.Exists())
        {
            Console.WriteLine(string.Format("Destination blob '{0}' already exists. Skipping.", destinationBlob.Uri));
        }
        else
        {
            try
            {
                Console.WriteLine(string.Format("Copy blob '{0}' to '{1}'", sourceBlob.Uri, destinationBlob.Uri));
                destinationBlob.StartCopyFromBlob(new Uri(sourceBlob.Uri.AbsoluteUri + signature));
            }
            catch (Exception ex)
            {
                Console.WriteLine(string.Format("Error copying blob '{0}': {1}", sourceBlob.Name, ex.Message));
            }
        }
    }

    /// <summary>
    /// Sets a file with the .ism extension as a primary file.
    /// </summary>
    /// <param name="asset">The asset that contains the smooth streaming files.</param>
    static private void SetISMFileAsPrimary(IAsset asset)
    {
        var ismAssetFiles = asset.AssetFiles.ToList().
            Where(f => f.Name.EndsWith(".ism", StringComparison.OrdinalIgnoreCase)).ToArray();

        if (ismAssetFiles.Count() != 1)
            throw new ArgumentException("The asset should have only one, .ism file");

        ismAssetFiles.First().IsPrimary = true;
        ismAssetFiles.First().Update();
    }
}

另请参阅

本文是否对您有所帮助?
(1500 个剩余字符)
感谢您的反馈
显示:
© 2014 Microsoft