DEV Community

Ricardo Ferreira
Ricardo Ferreira

Posted on AI-assisted

Replacing a dead ActiveX voice component with a small .NET speech API (and how to test it without a cloud key)

I work on software for the ATMs of a Brazilian bank. One of our modules reads the screen aloud for visually impaired customers. It is an accessible audio response module, and it works like a small voice guide: the ATM shows a step, and the customer hears what to do.

One day we had to change the phrases it speaks. The central bank of Brazil (Banco Central) required new wording for what we show to customers. If we did not change it, the bank would be fined.

That sounds like a small job. Change some text, ship. It was not, because the module was old, and the ATMs were old too.

The Problem: A Component That Could Not Be Changed

The ATMs run a legacy version of Windows. The drivers and the hardware cannot use a newer Windows, so upgrading the operating system was not an option.

The voice module had the same problem. Our code did not call ActiveX directly to speak. But the component we used was built on ActiveX, and ActiveX is not supported anymore. It does not work today. If you need to change it, or build a new application on top of it, that is impossible.

So the phrases were stuck inside something we could not modify. The legal change was small. The technical wall was not.

The Fix: Delete The Old Content, Build An API

We deleted the old ActiveX content and built an API in its place. The API sends the text to Microsoft's speech service in Azure. All the processing happens in the Microsoft cloud. The API gives us back the finished audio stream, and the ATM only plays it to the customer.

An honest note about the result. There was no real gain. The goal was to meet the legal demand from the central bank, because otherwise we would be fined. The new design also means the module no longer depends on a component that has no support.

The rest of this article shows the shape of that API in a small sample project. It is not the production code. It is a demo I wrote for this article, and it is tested without any Azure account.

The Design: One Interface In Front Of The Speech Engine

The most useful decision was to keep the speech engine behind one small interface. The API knows only this:

public interface ISpeechSynthesizer
{
    Task<byte[]> SynthesizeAsync(string text, CancellationToken cancellationToken);
}
Enter fullscreen mode Exit fullscreen mode

Text goes in, a WAV file (as bytes) comes out. The HTTP endpoint does not know about Azure, keys, or voices.

The endpoint is a minimal API:

app.MapPost("/speech", async (SpeechRequest request, ISpeechSynthesizer synthesizer,
    ILogger<Program> log, CancellationToken ct) =>
{
    if (string.IsNullOrWhiteSpace(request.Text) || request.Text.Length > 500)
        return Results.BadRequest("text is required and must have at most 500 characters");

    try
    {
        var wav = await synthesizer.SynthesizeAsync(request.Text, ct);
        return Results.File(wav, "audio/wav");
    }
    catch (Exception ex) when (ex is not OperationCanceledException)
    {
        log.LogError("Speech synthesis failed: {ErrorType}", ex.GetType().Name);
        return Results.StatusCode(StatusCodes.Status502BadGateway);
    }
});
Enter fullscreen mode Exit fullscreen mode

Three small choices here are worth explaining.

First, the 500 character limit. These are short phrases for a screen. A limit protects the cloud call from huge or empty requests, and it returns a clear 400 instead of a confusing failure later.

Second, 502 when the synthesizer fails. The client did nothing wrong, and our service did not break by itself. The service behind us failed. Bad Gateway says exactly that, so the caller can decide to retry or show a fallback.

Third, the log line. It writes only the exception type, never the text. A phrase can contain user data, and logs live longer than people expect.

The Real SDK, As A Snippet

This is the implementation that talks to Azure. It uses the Microsoft.CognitiveServices.Speech package (the Azure Speech SDK):

public sealed class AzureSpeechSynthesizer : ISpeechSynthesizer
{
    private readonly SpeechConfig _config;

    public AzureSpeechSynthesizer(string key, string region, string voice)
    {
        _config = SpeechConfig.FromSubscription(key, region);
        _config.SpeechSynthesisVoiceName = voice;
        _config.SetSpeechSynthesisOutputFormat(
            SpeechSynthesisOutputFormat.Riff16Khz16BitMonoPcm);
    }

    public async Task<byte[]> SynthesizeAsync(string text, CancellationToken cancellationToken)
    {
        using var synthesizer = new SpeechSynthesizer(_config, null);
        using var result = await synthesizer.SpeakTextAsync(text);

        if (result.Reason == ResultReason.SynthesizingAudioCompleted)
            return result.AudioData;

        var details = SpeechSynthesisCancellationDetails.FromResult(result);
        throw new InvalidOperationException($"Speech synthesis failed: {details.Reason}");
    }
}
Enter fullscreen mode Exit fullscreen mode

What each part does:

  • SpeechConfig holds the key, the region and the voice. The sample default is the Brazilian Portuguese neural voice pt-BR-FranciscaNeural.
  • The output format asks for a RIFF container, which is a normal WAV file. Without it, the caller would get raw audio that a player cannot open directly.
  • Passing null as the second argument of SpeechSynthesizer means "do not play this on the server speakers". The audio stays in memory, and we get it through result.AudioData.
  • One limit of my sample: SynthesizeAsync receives a CancellationToken, but SpeakTextAsync is called without it, so a cancelled request does not stop the cloud call. For a short phrase I accepted that. A production version should handle it.
  • If the result is not SynthesizingAudioCompleted, the SDK can tell us why through SpeechSynthesisCancellationDetails. We turn that into an exception, and the endpoint turns the exception into a 502.

I checked the SDK calls against the Microsoft Learn text-to-speech quickstart for the SDK.

One thing I want to say clearly. The demo repository compiles this class in CI, but it never calls it. I did not create an Azure account for the article, so this class was not run against the real service in the sample. In the real project, the replacement for ActiveX uses this same library, Microsoft.CognitiveServices.Speech.

Testing Without Azure

Because the API depends only on the interface, a test can replace the real engine with a fake. The fake returns a valid, silent WAV file of 0.1 seconds:

class FakeSynthesizer : ISpeechSynthesizer
{
    public Task<byte[]> SynthesizeAsync(string text, CancellationToken cancellationToken)
    {
        const int sampleRate = 16000;
        var data = new byte[sampleRate / 10 * 2];
        using var ms = new MemoryStream();
        using var w = new BinaryWriter(ms);
        w.Write(Encoding.ASCII.GetBytes("RIFF"));
        w.Write(36 + data.Length);
        w.Write(Encoding.ASCII.GetBytes("WAVEfmt "));
        w.Write(16); w.Write((short)1); w.Write((short)1);
        w.Write(sampleRate); w.Write(sampleRate * 2); w.Write((short)2); w.Write((short)16);
        w.Write(Encoding.ASCII.GetBytes("data"));
        w.Write(data.Length); w.Write(data);
        return Task.FromResult(ms.ToArray());
    }
}
Enter fullscreen mode Exit fullscreen mode

The tests use WebApplicationFactory to start the real API in memory and swap the synthesizer:

private static HttpClient CreateClient(ISpeechSynthesizer synthesizer) =>
    new WebApplicationFactory<Program>()
        .WithWebHostBuilder(b => b.ConfigureTestServices(s =>
            s.AddSingleton(synthesizer)))
        .CreateClient();

[Fact]
public async Task Speech_ValidText_ReturnsWav()
{
    var client = CreateClient(new FakeSynthesizer());

    var response = await client.PostAsJsonAsync("/speech", new { text = "Retire seu cartão." });
    var bytes = await response.Content.ReadAsByteArrayAsync();

    Assert.Equal(HttpStatusCode.OK, response.StatusCode);
    Assert.Equal("audio/wav", response.Content.Headers.ContentType?.MediaType);
    Assert.Equal("RIFF", Encoding.ASCII.GetString(bytes, 0, 4));
    Assert.Equal("WAVE", Encoding.ASCII.GetString(bytes, 8, 4));
}
Enter fullscreen mode Exit fullscreen mode

The project has four tests, and one of them runs with two inputs (empty text and blank text):

  • A valid phrase returns 200, the audio/wav content type, and a file that starts with the RIFF and WAVE markers.
  • Empty or blank text returns 400.
  • A text with 501 characters returns 400.
  • A synthesizer that throws returns 502.

The test log shows the line "Speech synthesis failed: InvalidOperationException". That is expected. It comes from the 502 test, and it proves that the log writes the error type and not the phrase.

To be exact about what these tests prove: they prove the API contract. Validation, status codes, content type, and error handling. They do not prove that Azure produces good audio, that the voice sounds right, or that the network is fast enough. Those need a real key and a real listener, ideally a customer who uses the module.

Startup is also lazy on purpose. The Azure synthesizer is registered with a factory, so it is created on the first request that needs it. The application, and the tests, start without any key configured.

Running It

Clone the repository, then:

dotnet test tests/Tests.csproj
Enter fullscreen mode Exit fullscreen mode

To run it for real, set Speech_Key and Speech_Region and start it:

dotnet run --project src
Enter fullscreen mode Exit fullscreen mode

Then send a POST to /speech with {"text": "..."} and save the response as a .wav file.

What I Would Tell Someone In The Same Situation

  1. A deadline from a regulator can expose old technical debt. The text change was easy. The platform under it was the problem.
  2. Do not wait for the hardware to catch up if the logic can move. We could not change the ATM's Windows, but we could move the speech out of the old component and into a service.
  3. Put the engine behind an interface from day one. It made the code testable without a cloud account, and it makes a future change of provider a one-class change.
  4. Be honest about the gain. Sometimes the result is "we met the legal demand", not "it got faster". That is still a good reason to do the work.

The sample code is on GitHub: https://github.com/rafengenharia/speech-api-activex-replacement-dotnet

Top comments (0)