Skip to content

Commit

Permalink
Add token auth sample for batch synthesis (#2744)
Browse files Browse the repository at this point in the history
* Fix legacy voice

* Enhance Batch Synthesis Client to support token-based authentication and update README with authentication options
  • Loading branch information
Ling-Cao authored Feb 21, 2025
1 parent d80910d commit 32eb3a2
Show file tree
Hide file tree
Showing 4 changed files with 47 additions and 19 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,27 +6,33 @@
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Net.Http.Headers;

public class BatchSynthesisClient
{
private const string OcpApimSubscriptionKey = "Ocp-Apim-Subscription-Key";

private readonly string hostName;
private readonly string baseUri;
private readonly string subscriptionKey;
private readonly string apiVersion;

private readonly HttpClient client;

public BatchSynthesisClient(string hostName, string key, string apiVersion)
public BatchSynthesisClient(string hostName, string credential, string apiVersion, bool isToken = false)
{
this.hostName = hostName;
this.subscriptionKey = key;
this.baseUri = $"{this.hostName}/texttospeech/batchsyntheses";
this.apiVersion = apiVersion;

this.client = new HttpClient();
client.DefaultRequestHeaders.Add(OcpApimSubscriptionKey, this.subscriptionKey);
if (isToken)
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", credential);
}
else
{
client.DefaultRequestHeaders.Add(OcpApimSubscriptionKey, credential);
}
}

public async Task<IEnumerable<BatchSynthesis>> GetAllSynthesesAsync()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
<ItemGroup>
<PackageReference Include="Microsoft.AspNet.WebApi.Client" version="5.2.7" PrivateAssets="All" />
<PackageReference Include="Newtonsoft.Json" version="13.0.1" PrivateAssets="All" />
<PackageReference Include="Azure.Identity" Version="1.13.2" />
</ItemGroup>
<ItemGroup>
<Content Include="..\..\Gatsby-chapter1.txt">
Expand Down
36 changes: 26 additions & 10 deletions samples/batch-synthesis/csharp/BatchSynthesisSample/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,35 @@
// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.
//

// Your Speech resource key and region
// This example requires environment variables named "SPEECH_KEY" and "SPEECH_REGION"
string speechRegion = Environment.GetEnvironmentVariable("SPEECH_REGION")
?? throw new ArgumentException("Please set SPEECH_REGION environment variable.");
using Azure.Core;
using Azure.Identity;

string speechKey = Environment.GetEnvironmentVariable("SPEECH_KEY")
?? throw new ArgumentException("Please set the SPEECH_KEY environment variable to set speech resource key.");
// The endpoint (and key) could be gotten from the Keys and Endpoint page in the Speech service resource.
// The endpoint would be like: https://<region>.api.cognitive.microsoft.com or https://<custom_domain>.cognitiveservices.azure.com
// If you want to use token authentication, custom domain is required.
var host = Environment.GetEnvironmentVariable("SPEECH_ENDPOINT");
BatchSynthesisClient synthesisClient;
var apiVersion = "2024-04-01";
if (!string.IsNullOrEmpty(host))
{
// Use Azure Identity SDK to acquire token
var credential = new DefaultAzureCredential();
var tokenRequestContext = new TokenRequestContext(new[] { "https://cognitiveservices.azure.com/.default" });
var accessToken = (await credential.GetTokenAsync(tokenRequestContext)).Token;

string apiVersion = "2024-04-01";
var host = $"https://{speechRegion}.api.cognitive.microsoft.com";
var sampleScript = await File.ReadAllTextAsync("../../Gatsby-chapter1.txt").ConfigureAwait(false);
// Use access token for authentication
synthesisClient = new BatchSynthesisClient(host, accessToken, apiVersion, isToken: true);
}
else
{
string speechRegion = Environment.GetEnvironmentVariable("SPEECH_REGION") ?? throw new ArgumentException("Please set either the SPEECH_REGION or SPEECH_ENDPOINT environment variable.");
string speechKey = Environment.GetEnvironmentVariable("SPEECH_KEY") ?? throw new ArgumentException("Please set either the SPEECH_KEY and SPEECH_REGION environment variables, or the SPEECH_ENDPOINT environment variable for authentication.");

host = $"https://{speechRegion}.api.cognitive.microsoft.com";
synthesisClient = new BatchSynthesisClient(host, speechKey, apiVersion);
}

var synthesisClient = new BatchSynthesisClient(host, speechKey, apiVersion);
var sampleScript = await File.ReadAllTextAsync("../../Gatsby-chapter1.txt").ConfigureAwait(false);

// Get all synthesis jobs.
var synthesisJobs = await synthesisClient.GetAllSynthesesAsync().ConfigureAwait(false);
Expand Down
15 changes: 10 additions & 5 deletions samples/batch-synthesis/csharp/BatchSynthesisSample/README.md
Original file line number Diff line number Diff line change
@@ -1,13 +1,18 @@
# C# Example to use the Speech Services Batch Synthesis API

To successfully run this example you require:
To successfully run this example, you must use one of the following authentication methods:

- A Speech Service subscription key
- The region information matching your subscription key
Option 1: Token-based authentication (Recommended)

- Set the Speech endpoint (set `SPEECH_ENDPOINT`)
- Ensure your Microsoft Entra account is assigned the "Cognitive Services Speech Contributor" or "Cognitive Services User" role.

Option 2: Key-based authentication

- Set the Speech Service subscription key (set `SPEECH_KEY`)
- Set the region matching your subscription key (set `SPEECH_REGION`)

Optionally:

- The relationship between custom voice names and deployment ID, if you want to use custom voices
- The URI of a writable Azure blob container, if you want to store the audio files in your own Azure storage

Set the environment variables `SPEECH_KEY` and `SPEECH_REGION` before running the program.

0 comments on commit 32eb3a2

Please sign in to comment.