Begin by craeting a Speech resource in the Azure portal. The free tier is valid for seven days and yields two interchangeable subscription keys plus a region identifier (for trial accounts the region is usually westus).
- Install the SDK
dotnet add package Microsoft.CognitiveServices.Speech
- Platform target
Open Configuration Manager and set the active solution platform to x64 (or x86 on 32-bit systems). The native libraries do not support Any CPU.
- Single-shot recognition from the microphone
using Microsoft.CognitiveServices.Speech;
using Microsoft.CognitiveServices.Speech.Audio;
public static async Task<string> TranscribeOnceAsync(string key, string region)
{
var cfg = SpeechConfig.FromSubscription(key, region);
cfg.SpeechRecognitionLanguage = "zh-CN";
using var reco = new SpeechRecognizer(cfg);
Console.WriteLine("Speak now...");
var outcome = await reco.RecognizeOnceAsync();
switch (outcome.Reason)
{
case ResultReason.RecognizedSpeech:
return outcome.Text;
case ResultReason.NoMatch:
return "(no speech detected)";
case ResultReason.Canceled:
var c = CancellationDetails.FromResult(outcome);
return $"[Canceled] {c.ErrorDetails}";
default:
return "(unknown)";
}
}
- Continuous recognition from a audio file
public static async Task TranscribeFileAsync(string key, string region, string wavPath)
{
var cfg = SpeechConfig.FromSubscription(key, region);
cfg.SpeechRecognitionLanguage = "zh-CN";
var finished = new TaskCompletionSource<int>();
using var input = AudioConfig.FromWavFileInput(wavPath);
using var reco = new SpeechRecognizer(cfg, input);
reco.Recognizing += (_, e) => Console.WriteLine($"Partial: {e.Result.Text}");
reco.Recognized += (_, e) => Console.WriteLine($"Final : {e.Result.Text}");
reco.Canceled += (_, e) => Console.WriteLine($"Canceled: {e.ErrorDetails}");
reco.SessionStarted += (_, _) => Console.WriteLine("Session started");
reco.SessionStopped += (_, _) => finished.TrySetResult(0);
await reco.StartContinuousRecognitionAsync();
await finished.Task;
await reco.StopContinuousRecognitionAsync();
}
Omit AudioConfig.FromWavFileInput to stream from the default microphone instead of a file.
- Quick timing helper
var sw = System.Diagnostics.Stopwatch.StartNew();
// ... recognition work ...
sw.Stop();
Console.WriteLine($"Elapsed {sw.ElapsedMilliseconds} ms");
More advanced scenarios—such as integrating with Language Understanding (LUIS) for intent extractino—are covered in the official documentation.