azure-ai/AzureAi.Transcriber/Services/TranscribeService.cs

43 lines
1.5 KiB
C#
Raw Normal View History

2024-05-08 10:14:57 +00:00
using Microsoft.CognitiveServices.Speech;
using Microsoft.CognitiveServices.Speech.Audio;
namespace AzureAi.Transcriber.Services;
public interface ITranscribeService
{
Task<SpeechRecognitionResult> Transcribe(string filePath);
}
public class TranscribeService: ITranscribeService
{
private static string _speechKey = Environment.GetEnvironmentVariable("SPEECH_KEY") ?? string.Empty;
private static string _speechRegion = Environment.GetEnvironmentVariable("SPEECH_REGION") ?? string.Empty;
private ILogger<TranscribeService> Logger;
public TranscribeService(ILogger<TranscribeService> logger)
{
Logger = logger;
if(string.IsNullOrWhiteSpace(_speechKey) || string.IsNullOrWhiteSpace(_speechRegion))
{
throw new InvalidOperationException("Speech key and region must be set in environment variables.");
}
}
public async Task<SpeechRecognitionResult> Transcribe(string filePath)
{
Logger.LogInformation("Transcribing {filePath}", filePath);
await Task.Delay(3000);
var speechConfig = SpeechConfig.FromSubscription(_speechKey, _speechRegion);
speechConfig.SpeechRecognitionLanguage = "en-US";
using var audioConfig = AudioConfig.FromWavFileInput(filePath);
using var recognizer = new SpeechRecognizer(speechConfig, audioConfig);
var result = await recognizer.RecognizeOnceAsync();
return result;
}
}