How to Upload Code to Api App Azure
This browser is no longer supported.
Upgrade to Microsoft Edge to have advantage of the latest features, security updates, and technical support.
Looking for Media Services v2 documentation?
Note
Fifty-fifty though this tutorial uses .Cyberspace SDK examples, the general steps are the same for REST API, CLI, or other supported SDKs.
Azure Media Services lets you encode your media files into formats that play on a wide variety of browsers and devices. For example, you might want to stream your content in Apple's HLS or MPEG DASH formats. Before streaming, you should encode your loftier-quality digital media file. For help with encoding, run into Encoding concept. This tutorial uploads a local video file and encodes the uploaded file. Yous tin also encode content that you brand accessible via an HTTPS URL.
This tutorial shows you how to:
- Download the sample app described in the topic.
- Examine the code that uploads, encodes, and streams.
- Run the app.
- Test the streaming URL.
- Make clean upwardly resources.
Prerequisites
- Install Visual Studio Code for Windows/macOS/Linux or Visual Studio 2019 for Windows or Mac.
- Install .NET five.0 SDK
- Create a Media Services account. Be sure to re-create the API Access details in JSON format or store the values needed to connect to the Media Services account in the .env file format used in this sample.
- Follow the steps in Admission the Azure Media Services API with the Azure CLI and relieve the credentials. You'll need to use them to admission the API in this sample, or enter them into the .env file format.
Download and configure the sample
Clone a GitHub repository that has the streaming .Net sample to your machine using the post-obit command:
git clone https://github.com/Azure-Samples/media-services-v3-dotnet-tutorials.git The sample is located in the UploadEncodeAndStreamFiles folder.
Open appsettings.json in your downloaded project. Supersede the values with credentials that you got from accessing APIs.
Notation
The .gitignore file is already configured to prevent publishing this file into your forked repository.
Examine the code that uploads, encodes, and streams
This department examines functions divers in the Programme.cs file of the UploadEncodeAndStreamFiles projection.
The sample performs the following actions:
- Creates a new Transform (first, checks if the specified Transform exists).
- Creates an output Asset that's used every bit the encoding Job'southward output.
- Create an input Asset and uploads the specified local video file into it. The nugget is used as the task'due south input.
- Submits the encoding job using the input and output that was created.
- Checks the task's status.
- Creates a Streaming Locator.
- Builds streaming URLs.
Start using Media Services APIs with the .NET SDK
To start using Media Services APIs with .NET, you need to create an AzureMediaServicesClient object. To create the object, you need to supply credentials for the client to connect to Azure past using Azure Active Directory. Some other pick is to utilize interactive authentication, which is implemented in GetCredentialsInteractiveAuthAsync.
public static async Task<IAzureMediaServicesClient> CreateMediaServicesClientAsync(ConfigWrapper config, bool interactive = false) { ServiceClientCredentials credentials; if (interactive) credentials = await GetCredentialsInteractiveAuthAsync(config); else credentials = await GetCredentialsAsync(config); render new AzureMediaServicesClient(config.ArmEndpoint, credentials) { SubscriptionId = config.SubscriptionId, }; } In the code that you cloned at the beginning of the article, the GetCredentialsAsync function creates the ServiceClientCredentials object based on the credentials supplied in the local configuration file (appsettings.json) or through the .env surround variables file in the root of the repository.
private static async Task<ServiceClientCredentials> GetCredentialsAsync(ConfigWrapper config) { // Utilise ConfidentialClientApplicationBuilder.AcquireTokenForClient to get a token using a service principal with symmetric key var scopes = new[] { config.ArmAadAudience + "/.default" }; var app = ConfidentialClientApplicationBuilder.Create(config.AadClientId) .WithClientSecret(config.AadSecret) .WithAuthority(AzureCloudInstance.AzurePublic, config.AadTenantId) .Build(); var authResult = await app.AcquireTokenForClient(scopes) .ExecuteAsync() .ConfigureAwait(fake); return new TokenCredentials(authResult.AccessToken, TokenType); } In the case of interactive authentication, the GetCredentialsInteractiveAuthAsync function creates the ServiceClientCredentials object based on an interactive hallmark and the connection parameters supplied in the local configuration file (appsettings.json) or through the .env environment variables file in the root of the repository. In that case, AADCLIENTID and AADSECRET are non needed in the configuration or environment variables file.
private static async Chore<ServiceClientCredentials> GetCredentialsInteractiveAuthAsync(ConfigWrapper config) { var scopes = new[] { config.ArmAadAudience + "/user_impersonation" }; // client awarding of Az Cli string ClientApplicationId = "04b07795-8ddb-461a-bbee-02f9e1bf7b46"; AuthenticationResult consequence = null; IPublicClientApplication app = PublicClientApplicationBuilder.Create(ClientApplicationId) .WithAuthority(AzureCloudInstance.AzurePublic, config.AadTenantId) .WithRedirectUri("http://localhost") .Build(); var accounts = await app.GetAccountsAsync(); endeavour { result = look app.AcquireTokenSilent(scopes, accounts.FirstOrDefault()).ExecuteAsync(); } catch (MsalUiRequiredException ex) { try { result = look app.AcquireTokenInteractive(scopes).ExecuteAsync(); } take hold of (MsalException maslException) { Console.Error.WriteLine($"ERROR: MSAL interactive authentication exception with code '{maslException.ErrorCode}' and bulletin '{maslException.Bulletin}'."); } } catch (MsalException maslException) { Console.Error.WriteLine($"ERROR: MSAL silent authentication exception with code '{maslException.ErrorCode}' and message '{maslException.Message}'."); } return new TokenCredentials(result.AccessToken, TokenType); } Create an input asset and upload a local file into it
The CreateInputAsset part creates a new input asset and uploads the specified local video file into information technology. This asset is used every bit the input to your encoding job. In Media Services v3, the input to a job can either be an asset or content that yous make available to your Media Services account via HTTPS URLs.
In Media Services v3, y'all utilize Azure Storage APIs to upload files. The following .Net snippet shows how.
The following part performs these actions:
-
Creates an Nugget.
-
Gets a writable SAS URL to the nugget'south container in storage.
If using asset's ListContainerSas function to become SAS URLs, note that the function returns multiple SAS URLs equally there are two storage account keys for each storage account. A storage business relationship has two keys because it allows for seamless rotation of storage account keys (for example, alter one while using the other then start using the new cardinal and rotate the other key). The 1st SAS URL represents storage key1 and second one storage key2.
-
Uploads the file into the container in storage using the SAS URL.
private static async Task<Nugget> CreateInputAssetAsync( IAzureMediaServicesClient client, string resourceGroupName, string accountName, string assetName, cord fileToUpload) { // In this instance, nosotros are assuming that the asset name is unique. // // If y'all already have an nugget with the desired name, apply the Assets.Get method // to get the existing asset. In Media Services v3, the Become method on entities returns naught // if the entity doesn't be (a example-insensitive bank check on the name). // Telephone call Media Services API to create an Nugget. // This method creates a container in storage for the Asset. // The files (blobs) associated with the asset will exist stored in this container. Asset nugget = await client.Assets.CreateOrUpdateAsync(resourceGroupName, accountName, assetName, new Nugget()); // Utilise Media Services API to get back a response that contains // SAS URL for the Asset container into which to upload blobs. // That is where y'all would specify read-write permissions // and the exparation fourth dimension for the SAS URL. var response = expect customer.Assets.ListContainerSasAsync( resourceGroupName, accountName, assetName, permissions: AssetContainerPermission.ReadWrite, expiryTime: DateTime.UtcNow.AddHours(4).ToUniversalTime()); var sasUri = new Uri(response.AssetContainerSasUrls.Beginning()); // Use Storage API to become a reference to the Nugget container // that was created by calling Asset's CreateOrUpdate method. BlobContainerClient container = new BlobContainerClient(sasUri); BlobClient blob = container.GetBlobClient(Path.GetFileName(fileToUpload)); // Apply Strorage API to upload the file into the container in storage. await blob.UploadAsync(fileToUpload); return nugget; } Create an output asset to store the consequence of a job
The output Asset stores the issue of your encoding task. The project defines the DownloadResults office that downloads the results from this output asset into the "output" folder, so you can meet what y'all got.
individual static async Chore<Asset> CreateOutputAssetAsync(IAzureMediaServicesClient client, cord resourceGroupName, cord accountName, string assetName) { bool existingAsset = true; Asset outputAsset; endeavour { // Check if an Asset already exists outputAsset = await client.Avails.GetAsync(resourceGroupName, accountName, assetName); } catch (ErrorResponseException ex) when (ex.Response.StatusCode == Organisation.Internet.HttpStatusCode.NotFound) { existingAsset = false; } Asset nugget = new Nugget(); string outputAssetName = assetName; if (existingAsset) { // Name collision! In club to go the sample to work, permit'due south just get ahead and create a unique nugget name // Note that the returned Asset can have a different name than the one specified as an input parameter. // You may desire to update this part to throw an Exception instead, and handle name collisions differently. string uniqueness = $"-{Guid.NewGuid():N}"; outputAssetName += uniqueness; Console.WriteLine("Warning – institute an existing Asset with proper name = " + assetName); Console.WriteLine("Creating an Asset with this name instead: " + outputAssetName); } render await client.Avails.CreateOrUpdateAsync(resourceGroupName, accountName, outputAssetName, asset); } Create a Transform and a Task that encodes the uploaded file
When encoding or processing content in Media Services, it's a common blueprint to prepare upwards the encoding settings every bit a recipe. You would then submit a Chore to utilize that recipe to a video. Past submitting new jobs for each new video, you lot're applying that recipe to all the videos in your library. A recipe in Media Services is chosen a Transform. For more information, meet Transforms and Jobs. The sample described in this tutorial defines a recipe that encodes the video in order to stream it to a variety of iOS and Android devices.
Transform
When creating a new Transform case, you demand to specify what you want it to produce as an output. The required parameter is a TransformOutput object, every bit shown in the lawmaking below. Each TransformOutput contains a Preset. Preset describes the step-by-footstep instructions of video and/or audio processing operations that are to be used to generate the desired TransformOutput. The sample described in this article uses a built-in Preset called AdaptiveStreaming. The Preset encodes the input video into an auto-generated bitrate ladder (bitrate-resolution pairs) based on the input resolution and bitrate, and produces ISO MP4 files with H.264 video and AAC audio corresponding to each bitrate-resolution pair. For data nearly this Preset, see auto-generating bitrate ladder.
Yous tin utilize a built-in EncoderNamedPreset or use custom presets.
When creating a Transform, you should beginning check if one already exists using the Get method, as shown in the code that follows. In Media Services v3, Get methods on entities return null if the entity doesn't be (a case-insensitive check on the proper noun).
individual static async Job<Transform> GetOrCreateTransformAsync( IAzureMediaServicesClient client, string resourceGroupName, string accountName, string transformName) { bool createTransform = false; Transform transform = cipher; try { // Does a transform already exist with the desired name? Presume that an existing Transform with the desired proper noun // likewise uses the same recipe or Preset for processing content. transform = customer.Transforms.Get(resourceGroupName, accountName, transformName); } grab (ErrorResponseException ex) when (ex.Response.StatusCode == Arrangement.Cyberspace.HttpStatusCode.NotFound) { createTransform = true; } if (createTransform) { // You lot need to specify what yous want it to produce as an output TransformOutput[] output = new TransformOutput[] { new TransformOutput { // The preset for the Transform is fix to 1 of Media Services congenital-in sample presets. // You tin customize the encoding settings by changing this to use "StandardEncoderPreset" class. Preset = new BuiltInStandardEncoderPreset() { // This sample uses the built-in encoding preset for Adaptive Bitrate Streaming. PresetName = EncoderNamedPreset.AdaptiveStreaming } } }; // Create the Transform with the output defined above transform = await client.Transforms.CreateOrUpdateAsync(resourceGroupName, accountName, transformName, output); } return transform; } Job
As mentioned above, the Transform object is the recipe and a Job is the bodily request to Media Services to apply that Transform to a given input video or audio content. The Job specifies information like the location of the input video, and the location for the output.
In this example, the input video has been uploaded from your local machine.
private static async Task<Job> SubmitJobAsync(IAzureMediaServicesClient client, string resourceGroupName, string accountName, string transformName, cord jobName, cord inputAssetName, cord outputAssetName) { // Use the proper name of the created input asset to create the job input. JobInput jobInput = new JobInputAsset(assetName: inputAssetName); JobOutput[] jobOutputs = { new JobOutputAsset(outputAssetName), }; // In this case, we are assuming that the job name is unique. // // If you already have a job with the desired proper name, use the Jobs.Get method // to get the existing job. In Media Services v3, the Get method on entities returns cypher // if the entity doesn't exist (a case-insensitive cheque on the proper noun). Job job = await client.Jobs.CreateAsync( resourceGroupName, accountName, transformName, jobName, new Job { Input = jobInput, Outputs = jobOutputs, }); render task; } Wait for the Job to complete
The job takes some time to consummate and when it does y'all want to be notified. The code sample below shows how to poll the service for the status of the Task. Polling isn't a recommended all-time practice for production apps because of potential latency. Polling can be throttled if overused on an account. Developers should instead employ Outcome Filigree.
Outcome Grid is designed for high availability, consistent performance, and dynamic calibration. With Consequence Grid, your apps can mind for and react to events from nigh all Azure services, as well as custom sources. Uncomplicated, HTTP-based reactive event handling helps you lot build efficient solutions through intelligent filtering and routing of events. Run into Route events to a custom spider web endpoint.
The Job normally goes through the following states: Scheduled, Queued, Processing, Finished (the last state). If the job has encountered an error, yous get the Error state. If the chore is in the process of being canceled, y'all get Canceling and Canceled when it'due south done.
private static async Task<Job> WaitForJobToFinishAsync(IAzureMediaServicesClient client, string resourceGroupName, string accountName, string transformName, cord jobName) { const int SleepIntervalMs = twenty * 1000; Job task; exercise { task = await client.Jobs.GetAsync(resourceGroupName, accountName, transformName, jobName); Console.WriteLine($"Job is '{job.State}'."); for (int i = 0; i < job.Outputs.Count; i++) { JobOutput output = chore.Outputs[i]; Panel.Write($"\tJobOutput[{i}] is '{output.Land}'."); if (output.State == JobState.Processing) { Console.Write($" Progress (%): '{output.Progress}'."); } Console.WriteLine(); } if (job.Land != JobState.Finished && job.State != JobState.Error && chore.State != JobState.Canceled) { wait Task.Delay(SleepIntervalMs); } } while (task.Land != JobState.Finished && job.State != JobState.Error && job.State != JobState.Canceled); return job; } Chore mistake codes
See Error codes.
Get a Streaming Locator
After the encoding is complete, the next step is to make the video in the output Asset bachelor to clients for playback. You tin can go far available in two steps: first, create a Streaming Locator, and second, build the streaming URLs that clients tin can use.
The process of creating a Streaming Locator is called publishing. By default, the Streaming Locator is valid immediately afterwards you make the API calls, and lasts until it'due south deleted, unless you configure the optional get-go and end times.
When creating a StreamingLocator, you'll need to specify the desired StreamingPolicyName. In this instance, you'll be streaming in-the-clear (or non-encrypted content) so the predefined articulate streaming policy (PredefinedStreamingPolicy.ClearStreamingOnly) is used.
Of import
When using a custom Streaming Policy, you should design a express set up of such policies for your Media Service business relationship, and re-employ them for your StreamingLocators whenever the same encryption options and protocols are needed. Your Media Service account has a quota for the number of Streaming Policy entries. You shouldn't exist creating a new Streaming Policy for each Streaming Locator.
The following code assumes that you're calling the office with a unique locatorName.
private static async Task<StreamingLocator> CreateStreamingLocatorAsync( IAzureMediaServicesClient client, string resourceGroup, string accountName, string assetName, cord locatorName) { StreamingLocator locator = await customer.StreamingLocators.CreateAsync( resourceGroup, accountName, locatorName, new StreamingLocator { AssetName = assetName, StreamingPolicyName = PredefinedStreamingPolicy.ClearStreamingOnly }); return locator; } While the sample in this topic discusses streaming, you tin can use the same call to create a Streaming Locator for delivering video via progressive download.
Get streaming URLs
Now that the Streaming Locator has been created, yous can get the streaming URLs, equally shown in GetStreamingURLs. To build a URL, you demand to concatenate the Streaming Endpoint host name and the Streaming Locator path. In this sample, the default Streaming Endpoint is used. When y'all first create a Media Service account, this default Streaming Endpoint will be in a stopped state, and so you need to telephone call Start.
Notation
In this method, you need the locatorName that was used when creating the Streaming Locator for the output Asset.
private static async Task<IList<cord>> GetStreamingUrlsAsync( IAzureMediaServicesClient client, cord resourceGroupName, string accountName, Cord locatorName) { const string DefaultStreamingEndpointName = "default"; IList<cord> streamingUrls = new Listing<string>(); StreamingEndpoint streamingEndpoint = await client.StreamingEndpoints.GetAsync(resourceGroupName, accountName, DefaultStreamingEndpointName); if (streamingEndpoint.ResourceState != StreamingEndpointResourceState.Running) { wait client.StreamingEndpoints.StartAsync(resourceGroupName, accountName, DefaultStreamingEndpointName); } ListPathsResponse paths = wait client.StreamingLocators.ListPathsAsync(resourceGroupName, accountName, locatorName); foreach (StreamingPath path in paths.StreamingPaths) { UriBuilder uriBuilder = new UriBuilder { Scheme = "https", Host = streamingEndpoint.HostName, Path = path.Paths[0] }; streamingUrls.Add together(uriBuilder.ToString()); } return streamingUrls; } Make clean upward resource in your Media Services account
By and large, you should clean upward everything except objects that you're planning to reuse (typically, you'll reuse Transforms, and yous'll persist StreamingLocators, etc.). If yous desire your account to be clean after experimenting, delete the resources that you don't program to reuse. For case, the following code deletes the job, created assets and content key policy:
private static async Task CleanUpAsync( IAzureMediaServicesClient customer, string resourceGroupName, cord accountName, string transformName, string jobName, List<string> assetNames, string contentKeyPolicyName = null ) { wait customer.Jobs.DeleteAsync(resourceGroupName, accountName, transformName, jobName); foreach (var assetName in assetNames) { wait customer.Avails.DeleteAsync(resourceGroupName, accountName, assetName); } if (contentKeyPolicyName != zilch) { customer.ContentKeyPolicies.Delete(resourceGroupName, accountName, contentKeyPolicyName); } } Run the sample app
- Press Ctrl+F5 to run the EncodeAndStreamFiles app.
- Copy ane of the streaming URLs from the console.
This example displays URLs that tin can be used to play back the video using different protocols:
Test the streaming URL
To examination the stream, this article uses Azure Media Thespian.
Annotation
If a actor is hosted on an https site, make sure to update the URL to "https".
- Open a spider web browser and navigate to https://aka.ms/azuremediaplayer/.
- In the URL: box, paste i of the streaming URL values you got when you ran the app.
- Select Update Player.
Azure Media Player tin can be used for testing but shouldn't be used in a production environment.
Clean upward resources
If you no longer demand any of the resources in your resource grouping, including the Media Services and storage accounts yous created for this tutorial, delete the resource group you created earlier.
Execute the following CLI control:
az group delete --proper noun amsResourceGroup Multithreading
The Azure Media Services v3 SDKs aren't thread-safe. When developing a multi-threaded app, you should generate and employ a new AzureMediaServicesClient object per thread.
Source: https://docs.microsoft.com/en-us/azure/media-services/latest/stream-files-tutorial-with-api
0 Response to "How to Upload Code to Api App Azure"
Post a Comment