This blog will walk-through how you could access Windows Azure Media Services programmatically, and convert a .MP4 file into Smooth Streaming format. Before getting started, you should have the following items prepared:
- • Create a Media Services account in a new or existing Windows Azure subscription. If you don’t have one, you could check out my blog Getting started with Windows Azure Media Services.
- • Windows Azure SDK 1.6 (November 2011): [link]
- • Windows Azure Media Services SDK (June 2012 Preview): [link]
- • WCF Data Services 5.0 for OData V3: [link]
- • Visual Studio 2010 SP1 and .NET framework 3.5 SP1 and 4
Now, after installing all these, we could start coding. And you could download the finished code in case you couldn’t follow.
- 1. Create a console application in Visual Studio, fill in Name, location and click on OK.

- 2. Import all the references into your application:
- (1) You will need Windows Azure SDK from the following path C:\Program Files\Windows Azure SDK\v1.6\bin\
- • Microsoft.WindowsAzure.StorageClient.dll
- (2) And you will need WCF Data Services from C:\Program Files (x86)\Microsoft WCF Data Services\5.0\bin\.NETFramework\
- • Microsoft.Data.Edm.dll
- • Microsoft.Data.OData.dll
- • Microsoft.Data.Services.Client.dll
- • Microsoft.Data.Services.dll
- • System.Spatial.dll
- (3) Add Reference under .NET tab for
- • System.configuration
- (4) Add Media Service SDK from C:\Program Files (x86)\Microsoft SDKs\Windows Azure Media Services\Services SDK\v1.0\
- • Microsoft.WindowsAzure.MediaServices.Client.dll
3. Adding namespace in Program.cs file: using Microsoft.WindowsAzure.MediaSerivces.Client;
4. Prepare account name and account key to be used to connect to media services later. You should have the following code in program.cs file.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.WindowsAzure.MediaServices.Client; namespace mp4tosmoothstreaming { class Program { private static string accName = "YOUR_SERVICE_NAME"; private static string accKey = "YOUR_SERVICE_KEY"; static void Main(string[] args) { } } } |
You will need to substitute accName and accKey with what you seen in your portal (Manage Keys section). If you couldn’t find it, please refer to the last step of my another blog.
5. Connect to Windows Azure Media Services using CloudMediaContext by adding in another parameter under accKey.
|
1 |
private static CloudMediaContext mediaContext = null; |
Connect to media services inside Main method. After doing this, you could put a break line on the code blow and press F5 to compile this file. If you see mediaContext gets returned successfully, it means you have connected to Azure Media Services. Congrats!
|
1 |
mediaContext = new CloudMediaContext(accName, accKey); |
6. Now we will need to upload asset from input folder onto the cloud. Currently, we only support uploading asset from a local folder. We will adding support for uploading asset from a URL in the future.
Add in a name space called System.IO;
|
1 |
using System.IO; |
Add in two more global variables called inputPath and outputPath. inputPath indicates where you put your .MP4 file. For instance, if you put .Mp4 file into C:\input, your inputPath will be “C:\input\demo.mp4″, which points to the file. And outputPath is used to contain files you wish to download later after the encoding. If you don’t want to download any encoded files, you could skip this. Here is a sample .Mp4 file you could use. Below is the sample for my file path:
|
1 2 |
private static string inputPath = Path.GetFullPath(@"C:\tr\input\wldemo.mp4"); private static string outputPath = Path.GetFullPath(@"C:\tr\output"); |
7. Now we could create an asset from the inputPath you just defined. By adding the following line inside Main Method.
|
1 2 3 4 5 |
static void Main(string[] args) { mediaContext = new CloudMediaContext(accName, accKey); IAsset asset = mediaContext.Assets.Create(inputPath); } |
8. The next step is to encode the asset. We will create a method called CreateEncodingJob with the following signature.
|
1 2 3 |
static void CreateEncodingJob(IAsset asset, string outputFolder) { } |
9. Create a Job to encode your asset and get a Media processor. For our demo, we are going to encode Mp4 into Smooth Streaming format, so we will use MP4 to Smooth Streams Task. There are many other types of processors and you could read more on MSDN.
|
1 2 3 4 5 6 7 |
IJob job = mediaContext.Jobs.Create("My MP4 to Smooth job"); var theProcessor = from p in mediaContext.MediaProcessors where p.Name == "MP4 to Smooth Streams Task" select p; IMediaProcessor processor = theProcessor.First(); |
Here, we query processor based on String name using LINQ. And you could see the name we use here is “MP4 to Smooth Streams Task”.
10. You will also need a configuration file for Mp4 to Smooth Streams Task. This could be obtained here: Task Preset for MP4 to Smooth Streams Conversion. And Save the preset file locally and then load it into configuration data when you create a task. To save your time, I have upload the file here and you could put it into the same folder as input folder.
Add in a global variable configFilePath under outputPath:
|
1 2 3 |
private static string inputPath = Path.GetFullPath(@"C:\tr\input\wldemo.wmv"); private static string outputPath = Path.GetFullPath(@"C:\tr\output"); private static string configFilePath = Path.GetFullPath(@"C:\tr\input\MP4 to Smooth Streams.xml"); |
11. Adding a string configuration file to get a string format representation of the configuration XML you just used, inside CreateEncodingJob method as the following and create a task based on all parameters we just created.
|
1 2 3 4 5 |
string configuration = File.ReadAllText(configFilePath); ITask task = job.Tasks.AddNew("My Mp4 to Smooth Task", processor, configuration, TaskCreationOptions.ProtectedConfiguration); |
12. Lastly, specify InputMediaAsset and OutputMediaAsset in the task and submit your job for processing. The whole method should look like this:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
static void CreateEncodingJob(IAsset asset, string outputFolder) { IJob job = mediaContext.Jobs.Create("My MP4 to Smooth job"); var theProcessor = from p in mediaContext.MediaProcessors where p.Name == "MP4 to Smooth Streams Task" select p; IMediaProcessor processor = theProcessor.First(); string configuration = File.ReadAllText(configFilePath); ITask task = job.Tasks.AddNew("My Mp4 to Smooth Task", processor, configuration, TaskCreationOptions.ProtectedConfiguration); task.InputMediaAssets.Add(asset); task.OutputMediaAssets.AddNew("Output asset",true,AssetCreationOptions.None); job.Submit(); } |
13. We will need to call CreateEncodingJob from Main method in order to use this method:
|
1 2 3 4 5 6 7 8 |
static void Main(string[] args) { mediaContext = new CloudMediaContext(accName, accKey); IAsset asset = mediaContext.Assets.Create(inputPath); CreateEncodingJob(asset, outputPath); } |
14. We will also want to track job process after the job getting submitted. You could add the following code after job.submit() in CreateEncodingJob Method.
|
1 |
CheckJobProgress(job.Id); |
And add the CheckJobProgress method in program.cs file. This method basiclaly keeps tracking the job progress, whether its queue, scheduled or getting processed.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
private static void CheckJobProgress(string jobId) { // Flag to indicate when job state is finished. bool jobCompleted = false; // Expected polling interval in milliseconds. Adjust this // interval as needed based on estimated job completion times. const int JobProgressInterval = 10000; while (!jobCompleted) { // Get an updated reference to the job in case // reference gets 'stale' while thread waits. IJob theJob = GetJob(jobId); // Check job and report state. switch (theJob.State) { case JobState.Finished: jobCompleted = true; Console.WriteLine(""); Console.WriteLine("********************"); Console.WriteLine("Job state is: " + theJob.State + "."); Console.WriteLine("Please wait while local tasks complete..."); Console.WriteLine(); break; case JobState.Queued: case JobState.Scheduled: case JobState.Processing: Console.WriteLine("Job state is: " + theJob.State + "."); Console.WriteLine("Please wait..."); Console.WriteLine(); break; case JobState.Error: // Log error as needed. break; default: Console.WriteLine(theJob.State.ToString()); break; } // Wait for the specified job interval before checking state again. Thread.Sleep(JobProgressInterval); } } |
15. Lastly, we will get the streaming URL for the asset we just converted. For nimbus, we provide two types of URL: one is called SAS URL, which shows where your media file physically stored, and the other is called Origin URL, which represents where you could stream video from. You could either download assets from SAS URL and streaming it from your own server, or leverage on the power of cloud computing to stream video from Origin URL.
Adding the following code into CreateEncodingJob method after CheckJobProgress method. It should be like this:
|
1 2 3 4 5 6 7 8 9 10 11 |
// Checks job progress and prints to the console. CheckJobProgress(job.Id); // Get an updated job reference, after waiting for the job on the thread in the CheckJobProgress method. job = GetJob(job.Id); // Get a reference to the output asset from the job. IAsset outputAsset = job.OutputMediaAssets[0]; // You can get a streaming URL for the output asset. GetStreamingOriginLocator(outputAsset); |
And here is the code for get updated Job reference by Job ID:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
static IJob GetJob(string jobId) { // Use a Linq select query to get an updated reference by Id. var job = from j in mediaContext.Jobs where j.Id == jobId select j; // Return the job reference as an Ijob. IJob theJob = job.SingleOrDefault(); // Confirm whether job exists, and return. if (theJob != null) return theJob; else Console.WriteLine("Job does not exist."); return null; } |
16. Adding GetStreamingOriginLocator method in program.cs.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
static void GetStreamingOriginLocator(IAsset assetToStream) { var theManifest = from f in assetToStream.Files where f.Name.EndsWith(".ism") select f; IFileInfo manifestFile = theManifest.First(); IAccessPolicy streamingPolicy = mediacontext.AccessPolicies.Create("Streaming policy", TimeSpan.FromDays(10), AccessPermissions.Read); ILocator originLocator = mediacontext.Locators.CreateOriginLocator(assetToStream, streamingPolicy, DateTime.UtcNow.AddMinutes(-5)); string urlForClientStreaming = originLocator.Path + manifestFile.Name + "/manifest"; Console.WriteLine("URL to manifest for client streaming: "); Console.WriteLine(urlForClientStreaming); string outFilePath = Path.GetFullPath(outputPath + @"\" + "StreamingUrl.txt"); WriteToFile(outFilePath, urlForClientStreaming); } |
17. Lastly, adding WriteToFile method in program.cs in order to capture the streaming url in a text file format. So we could use it to stream video later on.
|
1 2 3 4 5 6 |
static void WriteToFile(string outFilePath, string fileContent) { StreamWriter sr = File.CreateText(outFilePath); sr.Write(fileContent); sr.Close(); } |
18. Then press F5 and run this project. If you couldn’t follow, you could download the project here. And remember to prepare the following:
- • Put wldemo.mp4 and MP4 to Smooth Streams.xml these two files into C:\tr\input folder
- • Create a output folder under C:\tr so that you will have C:\tr\output.
- • Substitute accKey and accName from the beginning of the file and you could check them in your media service windows azure portal. Here is the blog to help you find it (scroll to the last step).
19. After running it, you could see a StreamingUrl.txt file inside of the output folder. You will get a url ends with /manifest. If you have a existing Smooth Streaming player, you could use it to test. Otherwise, we have a free player hosted in the cloud to help you test: http://smf.cloudapp.net/healthmonitor. If you have questions on how to use it, you could check my blog here.
This is the print screen of my working demo:


2 Responses to DEMO Windows Azure Media Services – how to convert .mp4 to smooth streaming format