Programmatically Uploading Media Content using Windows Azure Media Services SDK & C#

In this post, have explained how to create a proof of concept to demonstrate how media files can be uploaded to the azure storage using the Media Services SDK. Just before writing code, it is very important to understand the basics of media services.  If you are interested only in code, scroll down to the end of this post.

What are Media Services?

Windows Azure Media Services offer the flexibility, scalability and reliability of a cloud platform to handle high quality media experiences.

In simple terms, Windows Azure Media Services allows you to upload media files, encode them, convert the formats, protect the media content, do on-demand streaming or live streaming. and Yes, you have complete support for programming if you are a developer.

If you are interested to learn the concepts in detail, please visit this page from windows azure main website.

Prerequisites for uploading media files to storage (Programmatically)
  1. Have a Windows Azure Account (Free Trial at least)
  2. Login & Create a Media Services account (In my case I created it as msguymediaservice).
  3. Obtain the Account Name and Key & keep them handy (Have written the steps after the prerequisites section)
  4. Have the below development environment
    • Operating Systems: Windows 7, Windows 2008 R2, or Windows 8.
    • .NET Framework 4.5 or .NET Framework 4.
    • Visual Studio 2012 or Visual Studio 2010 SP1 (Professional, Premium, or Ultimate).

To obtain the key and account name, after creating media services account in step 2 above, you can just click on it (as shown below)

The below screen will be displayed.

Then, click on the Manage Keys button (as shown above) to see the below dialog

Now, just copy the account name and primary media service access key and paste them in a notepad. We will be using these credentials for this proof of concept later.

To get content into media services, you must first create an asset (one or more media files together) and upload it to storage.

Once you have the development environment ready, use Nuget to install the Azure media service SDK

PM > Install-Package windowsazure.mediaservices

Here is the complete listing with explanation for uploading the video file to azure storage using media services. Create a console application and copy the below code.

        using System;
        using System.IO;
        using System.Configuration;
        using Microsoft.WindowsAzure;
        using Microsoft.WindowsAzure.MediaServices.Client;

       //Let us have a Global Handle for accessing the media services context
        static CloudMediaContext m_MediaContext;
       // Entry point to your console application
        static void Main(string[] args)
            //Get the server context. The Media Service Name & Access key are the inputs
            m_MediaContext = new CloudMediaContext("msguymediaservice", "/u4+RqlARQcRWti5OOtBewOEHEgzn/H6hiWOcXSGwZg=");

            //Upload the video file. Asset Creation Options can  Common Encryption Protected or Envelope Encryption Protected if you want to encrypt it 
            //during the process or leave it to None otherwise. Replace the below file path with the actual video file path on your machine
            UploadMedia(AssetCreationOptions.None, @"D:\sample_mpeg4.mp4");

        //Creates the asset and returns the object
        static private IAsset CreateAsset(string i_sAssetName, AssetCreationOptions i_AssetCreationOption)
            var objAsset = m_MediaContext.Assets.Create(i_sAssetName, i_AssetCreationOption);
            return objAsset;

        //Uploads the media file to Azure Storage after creating the asset
        static public void UploadMedia(AssetCreationOptions i_Option, string i_sFilePath)
            //Form a Name for asset
            var sDynamicAssetName = "Asset_" + DateTime.UtcNow.ToString();

            //Create a empty asset
            var objAsset = CreateAsset(sDynamicAssetName, i_Option);

            //Get filename with extension which needs to be associated with asset
            var fileName = Path.GetFileName(i_sFilePath);

            //Create the asset file
            var objAssetFile = objAsset.AssetFiles.Create(fileName);
            Console.WriteLine("Created assetFile {0}", objAssetFile.Name);

            //Create an AccessPolicy instance that defines the permissions and duration of access to the asset.
            var accessPolicy = m_MediaContext.AccessPolicies.Create(sDynamicAssetName, TimeSpan.FromDays(3), AccessPermissions.Write | AccessPermissions.List);

            //Create a Locator instance that provides access to the asset.
            var locator = m_MediaContext.Locators.CreateLocator(LocatorType.Sas, objAsset, accessPolicy);

            Console.WriteLine("Upload {0}", objAssetFile.Name);

            //Updoad the asset to Azure Storage

            Console.WriteLine("Done uploading of {0} using Upload()", objAssetFile.Name);

            //Finally, Some Cleanup

Now, run the project. The code will create asset and upload it to the storage on your account automatically.

Once the upload is complete, just login to your azure account and verify.

Now, from the azure portal, You may publish your video in one click (ref. screenshot below. You can see a button). Once you publish it, you should see a publish URL for the video which you can use !!.

For a list of supported Media file formats, click here. You can also upload multiple files, upload even asynchronously & get the progress of the upload. I will leave this part to you. You can also program Media Services using the OData-based REST APIs. I will explain this part in an other post in the near future. Hope this post was useful. Your feedback and comments are welcome.

Popular posts from this blog

Facebook Javascript API : Feed and Share Dialog for Beginners

Developing a Link Chopper using C# and API in 1 Hour

WCF: Operation Overloading inside Service Contracts using C#