TTS .NET Quickstart Guide

Step-by-step guide for integrating the TTS API using Hume’s .NET SDK.

This guide shows how to get started using Hume’s Text-to-Speech capabilities in .NET using Hume’s .NET SDK. It demonstrates:

  1. Converting text to speech with a new voice.
  2. Saving a voice to your voice library for future use.
  3. Giving “acting instructions” to modulate the voice.
  4. Generating multiple variations of the same text at once.
  5. Providing context to maintain consistency across multiple generations.

The complete code for the example in this guide is available on GitHub.

Environment Setup

Create a new .NET project and install the required packages:

dotnet CLI
dotnet new console -n TtsCsharpQuickstart
cd TtsCsharpQuickstart
dotnet add package HumeApi

Authenticating the HumeApiClient

You must authenticate to use the Hume TTS API. Your API key can be retrieved from the Hume AI platform.

This example uses environment variables. Set your API key as an environment variable:

Environment Variable
# On Windows
set HUME_API_KEY=your_api_key_here
# On macOS/Linux
export HUME_API_KEY=your_api_key_here

Then create a new file Program.cs and use your API key to instantiate the HumeApiClient.

using System;
using HumeApi;
var apiKey = Environment.GetEnvironmentVariable("HUME_API_KEY");
if (string.IsNullOrEmpty(apiKey))
{
throw new InvalidOperationException("HUME_API_KEY not found in environment variables.");
}
var client = new HumeApiClient(apiKey);

Helper function

Define a function to aid in writing generated audio to a temporary file:

using System.IO;
using System.Threading.Tasks;
// Create an output directory in the temporary folder
var timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
var outputDir = Path.Combine(Path.GetTempPath(), $"hume-audio-{timestamp}");
Directory.CreateDirectory(outputDir);
Console.WriteLine($"Results will be written to {outputDir}");
static async Task WriteResultToFile(string base64EncodedAudio, string filename, string outputDir)
{
var filePath = Path.Combine(outputDir, $"{filename}.wav");
// Decode the base64-encoded audio data
var audioData = Convert.FromBase64String(base64EncodedAudio);
await File.WriteAllBytesAsync(filePath, audioData);
Console.WriteLine($"Wrote {filePath}");
}

Calling Text-to-Speech

To use Hume TTS, you can call client.Tts.SynthesizeJsonAsync with a SynthesizeJsonRequest containing a list of utterances. Inside each utterance, put the Text to speak, and optionally provide a Description of how the voice speaking the text should sound. If you don’t provide a description, Hume will examine Text and attempt to determine an appropriate voice.

The base64-encoded bytes of an audio file with your speech will be present at .Generations[0].Audio in the returned object. By default, there will only be a single variation in the .Generations array, and the audio will be in wav format.

The .Generations[0].GenerationId field will contain an ID you can use to refer to this specific generation of speech in future requests.

using HumeApi.Tts;
var speech1 = await client.Tts.SynthesizeJsonAsync(new SynthesizeJsonRequest
{
Body = new PostedTts
{
Utterances = new List<PostedUtterance>
{
new PostedUtterance
{
Description = "A refined, British aristocrat",
Text = "Take an arrow from the quiver."
}
}
}
});
await WriteResultToFile(speech1.Generations.First().Audio, "speech1_0", outputDir);

Saving voices

Use client.Tts.Voices.CreateAsync to save the voice of a generated piece of audio to your voice library for future use:

var name = $"aristocrat-{DateTimeOffset.UtcNow.ToUnixTimeSeconds()}";
var generationId = speech1.Generations.First().GenerationId;
await client.Tts.Voices.CreateAsync(new PostedVoice
{
Name = name,
GenerationId = generationId
});

Continuity

Inside an utterance, specify the name or ID of a voice to generate more speech from that voice.

To generate speech that is meant to follow previously generated speech, specify Context with the GenerationId of that speech.

You can specify a number up to 5 in NumGenerations to generate multiple variations of the same speech at the same time.

var speech2 = await client.Tts.SynthesizeJsonAsync(new SynthesizeJsonRequest
{
Body = new PostedTts
{
Utterances = new List<PostedUtterance>
{
new PostedUtterance
{
// Using a voice from your voice library
Voice = new PostedUtteranceVoiceWithName { Name = name },
Text = "Now take a bow."
}
},
// Providing previous context to maintain consistency.
// This should cause "bow" to rhyme with "toe" and not "cow".
Context = new PostedContextWithGenerationId { GenerationId = generationId },
NumGenerations = 2
}
});
await WriteResultToFile(speech2.Generations.First().Audio, "speech2_0", outputDir);
await WriteResultToFile(speech2.Generations.Skip(1).First().Audio, "speech2_1", outputDir);

Acting Instructions

If you specify both Voice and Description, the Description field will behave as “acting instructions”. It will keep the character of the specified Voice, but modulated to match Description.

var speech3 = await client.Tts.SynthesizeJsonAsync(new SynthesizeJsonRequest
{
Body = new PostedTts
{
Utterances = new List<PostedUtterance>
{
new PostedUtterance
{
Voice = new PostedUtteranceVoiceWithName { Name = name },
Description = "Murmured softly, with a heavy dose of sarcasm and contempt",
Text = "Does he even know how to use that thing?"
}
},
Context = new PostedContextWithGenerationId
{
GenerationId = speech2.Generations.First().GenerationId
},
NumGenerations = 1
}
});
await WriteResultToFile(speech3.Generations.First().Audio, "speech3_0", outputDir);

Streaming speech

You can stream utterances using the SynthesizeJsonStreamingAsync method. This allows you to process audio chunks as they become available rather than waiting for the entire speech generation to complete.

You can either write these chunks to files as we’ve done above, or play them in real-time with an audio player. Below is an example of real-time playback using a pipe-based streaming audio player:

using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Collections.Concurrent;
using System.Threading;
// Real-time streaming audio player using pipe-based approach
public class StreamingAudioPlayer : IDisposable
{
private Process? _audioProcess;
private int _chunkCounter = 0;
private bool _isStreaming = false;
public Task StartStreamingAsync()
{
_isStreaming = true;
StartAudioProcess();
Console.WriteLine("Streaming audio player started...");
return Task.CompletedTask;
}
public Task SendAudioAsync(byte[] audioBytes)
{
if (!_isStreaming || _audioProcess?.HasExited != false) return Task.CompletedTask;
try
{
_audioProcess?.StandardInput.BaseStream.Write(audioBytes, 0, audioBytes.Length);
_audioProcess?.StandardInput.BaseStream.Flush();
}
catch (Exception ex)
{
Console.WriteLine($"Error sending audio chunk: {ex.Message}");
}
return Task.CompletedTask;
}
public async Task StopStreamingAsync()
{
_isStreaming = false;
try
{
if (_audioProcess != null && !_audioProcess.HasExited)
{
_audioProcess.StandardInput.Close();
await _audioProcess.WaitForExitAsync();
}
}
catch (Exception ex)
{
Console.WriteLine($"Error stopping audio process: {ex.Message}");
}
Console.WriteLine("Streaming audio player stopped.");
}
private void StartAudioProcess()
{
try
{
var startInfo = new ProcessStartInfo
{
FileName = "ffplay",
Arguments = "-nodisp -autoexit -infbuf -i -",
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardInput = true,
RedirectStandardError = true,
RedirectStandardOutput = true
};
_audioProcess = Process.Start(startInfo);
if (_audioProcess == null)
{
throw new InvalidOperationException("Failed to start ffplay process");
}
_audioProcess.ErrorDataReceived += (sender, e) => {
if (!string.IsNullOrEmpty(e.Data))
Console.WriteLine($"ffplay: {e.Data}");
};
_audioProcess.BeginErrorReadLine();
}
catch (Exception ex)
{
Console.WriteLine($"Failed to start ffplay: {ex.Message}");
Console.WriteLine("Please install ffmpeg to enable streaming audio playback.");
}
}
public void Dispose()
{
try
{
if (_audioProcess != null && !_audioProcess.HasExited)
{
_audioProcess.Kill();
}
_audioProcess?.Dispose();
}
catch { }
}
}
private static StreamingAudioPlayer GetStreamingAudioPlayer()
{
return new StreamingAudioPlayer();
}
// Streaming example with real-time audio playback
Console.WriteLine("Streaming audio in real-time...");
var voice = new PostedUtteranceVoiceWithName { Name = name };
using var streamingPlayer = GetStreamingAudioPlayer();
await streamingPlayer.StartStreamingAsync();
await foreach (var snippet in client.Tts.SynthesizeJsonStreamingAsync(new PostedTts
{
Context = new PostedContextWithGenerationId
{
GenerationId = speech3.Generations.First().GenerationId
},
Utterances = new List<PostedUtterance>
{
new PostedUtterance { Text = "He's drawn the bow...", Voice = voice },
new PostedUtterance { Text = "he's fired the arrow...", Voice = voice },
new PostedUtterance { Text = "I can't believe it! A perfect bullseye!", Voice = voice }
},
Format = new Format(new Format.Wav()),
StripHeaders = true,
}))
{
await streamingPlayer.SendAudioAsync(Convert.FromBase64String(snippet.Audio));
}
await streamingPlayer.StopStreamingAsync();

Running the Example

dotnet run