Live transcribe audio from a microphone with Foundry Local

Use Foundry Local's live audio transcription API to stream microphone audio and receive transcription results in real time. In this article, you create a console application that captures audio from your microphone, streams it to a local speech model, and prints transcription output as you speak.

Prerequisites

  • .NET 9.0 SDK or later installed.
  • A working microphone connected to your computer.

Samples repository

The complete sample code for this article is available in the foundry-samples GitHub repository. To clone the repository and navigate to the sample use:

git clone https://github.com/microsoft-foundry/foundry-samples.git
cd foundry-samples/samples/csharp/foundry-local/live-audio-transcription-example

Install packages

dotnet add package Microsoft.AI.Foundry.Local
dotnet add package OpenAI

The C# samples in the GitHub repository are preconfigured projects. If you're building from scratch, you should read the Foundry Local SDK reference for more details on how to set up your C# project with Foundry Local.

Install the NAudio package for microphone capture:

dotnet add package NAudio

Live transcribe from microphone

The following code initializes the Foundry Local SDK, loads a streaming speech model, captures audio from your microphone using NAudio, and streams it to the live transcription API. Partial results appear as you speak, and final results are printed on a new line.

Copy and paste the following code into Program.cs:

// Live Audio Transcription — Foundry Local SDK v2 Example
//
// NAudio's WaveInEvent is Windows-only. On non-Windows platforms, the sample
// falls back to synthetic PCM audio.

using Microsoft.AI.Foundry.Local;
#if WINDOWS
using NAudio.Wave;
#endif

Console.WriteLine("===========================================================");
Console.WriteLine("   Foundry Local -- Live Audio Transcription Demo");
Console.WriteLine("===========================================================");
Console.WriteLine();

var config = new Configuration
{
    AppName = "foundry_local_samples",
    LogLevel = Microsoft.AI.Foundry.Local.LogLevel.Information
};

await FoundryLocalManager.CreateAsync(config, Utils.GetAppLogger());
var mgr = FoundryLocalManager.Instance;

await Utils.RunWithSpinner("Registering execution providers", mgr.DownloadAndRegisterEpsAsync());

var catalog = await mgr.GetCatalogAsync();

// English-only:
var modelAlias = "nemotron-speech-streaming-en-0.6b";
// Multi-lingual (supports 30+ languages including auto-detect):
// var modelAlias = "nvidia-nemotron-3.5-asr-streaming-multilingual-0.6b";

var model = await catalog.GetModelAsync(modelAlias)
    ?? throw new Exception($"Model \"{modelAlias}\" not found in catalog");

await model.DownloadAsync(progress =>
{
    Console.Write($"\rDownloading model: {progress:F2}%");
    if (progress >= 100f)
    {
        Console.WriteLine();
    }
});

Console.Write($"Loading model {model.Id}...");
await model.LoadAsync();
Console.WriteLine("done.");

using (var audioSession = new AudioSession(model))
using (var inputQueue = new ItemQueue())
using (var request = new Request())
{
    audioSession.SetOptions(new RequestOptions
    {
        AdditionalOptions = new Dictionary<string, string> { ["language"] = "en" }
    });
    audioSession.SetStreaming(true);

    request.AddItem(AudioItem.CreateFormatDescriptor("pcm", 16000, 1));
    request.AddItem(inputQueue, takeOwnership: false);

    await using var stream = audioSession.ProcessStreamingRequestAsync(request);
    var producer = Task.Run(() => ProduceAudioAsync(inputQueue, args.Contains("--synth")));

    await foreach (var item in stream)
    {
        using (item)
        {
            if (item is SpeechSegmentItem segment)
            {
                if (segment.Kind == SpeechSegmentKind.Final)
                {
                    Console.WriteLine();
                    Console.WriteLine($"  [FINAL] {segment.Text}");
                }
                else if (!string.IsNullOrEmpty(segment.Text))
                {
                    Console.ForegroundColor = ConsoleColor.Cyan;
                    Console.Write(segment.Text);
                    Console.ResetColor();
                }
                Console.Out.Flush();
            }
        }
    }

    await producer;
    using var finalResponse = await stream.FinalResponse;
    var transcript = finalResponse.OfType<SpeechResultItem>().FirstOrDefault()?.Text;
    if (!string.IsNullOrWhiteSpace(transcript))
    {
        Console.WriteLine($"\nTranscript: {transcript}");
    }
}

await model.UnloadAsync();

static async Task ProduceAudioAsync(ItemQueue inputQueue, bool useSynth)
{
    try
    {
        if (!useSynth && OperatingSystem.IsWindows())
        {
            await CaptureMicrophoneAsync(inputQueue);
        }
        else
        {
            if (!OperatingSystem.IsWindows() && !useSynth)
            {
                Console.WriteLine("NAudio mic capture is Windows-only. Falling back to synthetic audio...");
            }
            await PushSyntheticAudioAsync(inputQueue);
        }
    }
    finally
    {
        inputQueue.MarkFinished();
    }
}

static async Task CaptureMicrophoneAsync(ItemQueue inputQueue)
{
#if WINDOWS
    using var waveIn = new WaveIn
    {
        WaveFormat = new WaveFormat(rate: 16000, bits: 16, channels: 1),
        BufferMilliseconds = 100
    };

    var audioChannel = System.Threading.Channels.Channel.CreateBounded<byte[]>(
        new System.Threading.Channels.BoundedChannelOptions(50)
        {
            FullMode = System.Threading.Channels.BoundedChannelFullMode.DropOldest
        });

    waveIn.DataAvailable += (_, e) =>
    {
        if (e.BytesRecorded > 0)
        {
            var buffer = new byte[e.BytesRecorded];
            Buffer.BlockCopy(e.Buffer, 0, buffer, 0, e.BytesRecorded);
            audioChannel.Writer.TryWrite(buffer);
        }
    };

    Console.WriteLine();
    Console.WriteLine("===========================================================");
    Console.WriteLine("  LIVE TRANSCRIPTION ACTIVE");
    Console.WriteLine("  Speak into your microphone.");
    Console.WriteLine("  Transcription appears in real-time (cyan text).");
    Console.WriteLine("  Press ENTER to stop recording.");
    Console.WriteLine("===========================================================");
    Console.WriteLine();

    waveIn.StartRecording();
    var pushTask = Task.Run(async () =>
    {
        await foreach (var chunk in audioChannel.Reader.ReadAllAsync())
        {
            inputQueue.Push(BytesItem.CreateOwned(chunk));
        }
    });

    Console.ReadLine();
    waveIn.StopRecording();
    audioChannel.Writer.Complete();
    await pushTask;
#else
    await Task.CompletedTask;
    throw new PlatformNotSupportedException("Microphone capture requires Windows.");
#endif
}

static async Task PushSyntheticAudioAsync(ItemQueue inputQueue)
{
    Console.WriteLine("Pushing synthetic audio (440Hz sine, 2s)...");
    const int sampleRate = 16000;
    const int duration = 2;
    var totalSamples = sampleRate * duration;
    var pcmBytes = new byte[totalSamples * 2];
    for (var i = 0; i < totalSamples; i++)
    {
        var t = (double)i / sampleRate;
        var sample = (short)(short.MaxValue * 0.5 * Math.Sin(2 * Math.PI * 440 * t));
        pcmBytes[i * 2] = (byte)(sample & 0xFF);
        pcmBytes[i * 2 + 1] = (byte)((sample >> 8) & 0xFF);
    }

    var chunkSize = (sampleRate / 10) * 2;
    for (var offset = 0; offset < pcmBytes.Length; offset += chunkSize)
    {
        var length = Math.Min(chunkSize, pcmBytes.Length - offset);
        inputQueue.Push(BytesItem.CreateOwned(pcmBytes.AsMemory(offset, length)));
        await Task.Delay(100);
    }

    Console.WriteLine("✓ Synthetic audio pushed");
}

The CreateLiveTranscriptionSession method returns a session that accepts raw Pulse-code modulation (PCM) audio and yields transcription results as an async stream. NAudio's WaveInEvent captures microphone audio at 16-kHz mono—the format the session expects.

Run the application:

dotnet run

Speak into your microphone. You see real-time transcription output:

Listening... (press Ctrl+C to stop)
Hello, this is a test of the live transcription feature.
It transcribes audio from the microphone in real time.

Press Ctrl+C to stop recording. The model finishes processing any remaining audio and the application exits.

Prerequisites

  • Node.js version 20 or later installed.
  • A working microphone connected to your computer.

Samples repository

The complete sample code for this article is available in the foundry-samples GitHub repository. To clone the repository and navigate to the sample use:

git clone https://github.com/microsoft-foundry/foundry-samples.git
cd foundry-samples/samples/javascript/foundry-local/live-audio-transcription-example

Install packages

npm install foundry-local-sdk openai

Install the naudiodon2 package for microphone capture:

npm install naudiodon2

Live transcribe from microphone

The following code initializes the Foundry Local SDK, loads a streaming speech model, captures audio from your microphone using naudiodon2, and streams it to the live transcription API. Partial results appear as you speak, and final results are printed on a new line.

Copy and paste the following code into app.js:

// Live Audio Transcription Example — Foundry Local JS SDK
//
// Demonstrates real-time microphone-to-text using the JS SDK.
// Requires: npm install foundry-local-sdk naudiodon2
//
// Usage: node app.js

import {
    AudioSession,
    FoundryLocalManager,
    Item,
    ItemQueue,
    Request
} from 'foundry-local-sdk';

console.log('╔══════════════════════════════════════════════════════════╗');
console.log('║   Foundry Local — Live Audio Transcription (JS SDK)      ║');
console.log('╚══════════════════════════════════════════════════════════╝');
console.log();

// Initialize the Foundry Local SDK
console.log('Initializing Foundry Local SDK...');
const manager = FoundryLocalManager.create({
    appName: 'foundry_local_samples',
    logLevel: 'info'
});
console.log('✓ SDK initialized');

// Get and load the nemotron model
// English-only:
const modelAlias = 'nemotron-speech-streaming-en-0.6b';
// Multi-lingual (supports 30+ languages including auto-detect):
// const modelAlias = 'nvidia-nemotron-3.5-asr-streaming-multilingual-0.6b';
let model = await manager.catalog.getModel(modelAlias);
if (!model) {
    console.error(`ERROR: Model "${modelAlias}" not found in catalog.`);
    process.exit(1);
}

console.log(`Found model: ${model.id}`);
console.log('Downloading model (if needed)...');
await model.download((progress) => {
    process.stdout.write(`\rDownloading... ${progress.toFixed(2)}%`);
});
console.log('\n✓ Model downloaded');

console.log('Loading model...');
await model.load();
console.log('✓ Model loaded');

// Create a native streaming audio session.
const sampleRate = 16000;
const channels = 1;
const bitsPerSample = 16;
const language = 'en';
// Multi-lingual examples:
// const language = 'de';     // German
// const language = 'zh-CN';  // Chinese (Simplified)
// const language = 'auto';   // Auto-detect language

console.log('Starting streaming session...');
const audioSession = new AudioSession(model);
const audioQueue = new ItemQueue();
const request = new Request()
    .addItem(Item.audioDescriptor('pcm', sampleRate, channels))
    .addItem(audioQueue)
    .setOptions({ additionalOptions: { language } });
const stream = audioSession.processStreamingRequest(request);
console.log('✓ Session started');

// Read transcription results in background
const readPromise = (async () => {
    try {
        for await (const item of stream) {
            if (item.type === 'speechSegment' && item.text) {
                if (item.kind === 'final') {
                    process.stdout.write(`\n  [FINAL] ${item.text}\n`);
                } else {
                    process.stdout.write(item.text);
                }
            }
        }
        const response = await stream.response;
        const result = response.output.find((item) => item.type === 'speechResult');
        if (result?.text) {
            process.stdout.write(`\n  [TRANSCRIPT] ${result.text}\n`);
        }
    } catch (err) {
        if (err.name !== 'AbortError') {
            console.error('Stream error:', err.message);
        }
    }
})();

// --- Microphone capture ---
// This example uses naudiodon2 for cross-platform audio capture.
// Install with: npm install naudiodon2
//
// If you prefer a different audio library, push PCM byte chunks into audioQueue.

let audioInput;
try {
    const { default: portAudio } = await import('naudiodon2');

    audioInput = portAudio.AudioIO({
        inOptions: {
            channelCount: channels,
            sampleFormat: bitsPerSample === 16
                ? portAudio.SampleFormat16Bit
                : portAudio.SampleFormat32Bit,
            sampleRate,
            // Larger chunk size lowers callback frequency and reduces overflow risk.
            framesPerBuffer: 3200,
            // Allow deeper native queue during occasional event-loop stalls.
            maxQueue: 64
        }
    });

    const appendQueue = [];
    let pumping = false;
    let warnedQueueDrop = false;

    const pumpAudio = async () => {
        if (pumping) return;
        pumping = true;
        try {
            while (appendQueue.length > 0) {
                const pcm = appendQueue.shift();
                audioQueue.push(Item.bytes(pcm));
            }
        } catch (err) {
            console.error('append error:', err.message);
        } finally {
            pumping = false;
            // Handle race where new data arrived after loop exit.
            if (appendQueue.length > 0) {
                void pumpAudio();
            }
        }
    };

    audioInput.on('data', (buffer) => {
        // Single copy: slice the underlying ArrayBuffer to get an independent Uint8Array.
        const copy = new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength).slice();

        // Keep a bounded queue to avoid unbounded memory growth.
        if (appendQueue.length >= 100) {
            appendQueue.shift();
            if (!warnedQueueDrop) {
                warnedQueueDrop = true;
                console.warn('Audio append queue overflow; dropping oldest chunk to keep stream alive.');
            }
        }

        appendQueue.push(copy);
        void pumpAudio();
    });

    console.log();
    console.log('════════════════════════════════════════════════════════════');
    console.log('  LIVE TRANSCRIPTION ACTIVE');
    console.log('  Speak into your microphone.');
    console.log('  Press Ctrl+C to stop.');
    console.log('════════════════════════════════════════════════════════════');
    console.log();

    audioInput.start();
} catch (err) {
    console.warn('⚠ Could not initialize microphone (naudiodon2 may not be installed).');
    console.warn('  Install with: npm install naudiodon2');
    console.warn('  Falling back to synthetic audio test...');
    console.warn();

    // Fallback: push 2 seconds of synthetic PCM (440Hz sine wave)
    const duration = 2;
    const totalSamples = sampleRate * duration;
    const pcmBytes = new Uint8Array(totalSamples * 2);
    for (let i = 0; i < totalSamples; i++) {
        const t = i / sampleRate;
        const sample = Math.round(32767 * 0.5 * Math.sin(2 * Math.PI * 440 * t));
        pcmBytes[i * 2] = sample & 0xFF;
        pcmBytes[i * 2 + 1] = (sample >> 8) & 0xFF;
    }

    // Push in 100ms chunks
    const chunkSize = (sampleRate / 10) * 2;
    for (let offset = 0; offset < pcmBytes.length; offset += chunkSize) {
        const len = Math.min(chunkSize, pcmBytes.length - offset);
        audioQueue.push(Item.bytes(pcmBytes.slice(offset, offset + len)));
    }

    console.log('✓ Synthetic audio pushed');
    console.log('Waiting briefly for final transcription results...');
    await new Promise((resolve) => setTimeout(resolve, 3000));
    audioQueue.markFinished();
    await readPromise;
    audioQueue.dispose();
    audioSession.dispose();
    await model.unload();
    console.log('✓ Done');
    process.exit(0);
}

// Handle graceful shutdown
process.on('SIGINT', async () => {
    console.log('\n\nStopping...');
    if (audioInput) {
        audioInput.quit();
    }
    audioQueue.markFinished();
    await readPromise;
    audioQueue.dispose();
    audioSession.dispose();
    await model.unload();
    console.log('✓ Done');
    process.exit(0);
});

The createLiveTranscriptionSession method returns a session that accepts raw PCM audio and yields transcription results as an async generator. The naudiodon2 AudioIO captures microphone audio at 16 kHz mono 16-bit — the format the session expects.

Run the application:

node app.js

Speak into your microphone. You see real-time transcription output:

Listening... (press Ctrl+C to stop)
Hello, this is a test of the live transcription feature.
It transcribes audio from the microphone in real time.

Press Ctrl+C to stop recording. The model finishes processing any remaining audio and the application exits.

Prerequisites

  • Python 3.11 or later installed.
  • A working microphone connected to your computer.

Samples repository

The complete sample code for this article is available in the foundry-samples GitHub repository. To clone the repository and navigate to the sample use:

git clone https://github.com/microsoft-foundry/foundry-samples.git
cd foundry-samples/samples/python/foundry-local/live-audio-transcription

Install packages

pip install foundry-local-sdk openai

Install PyAudio for microphone capture:

pip install pyaudio

Live transcribe from microphone

The following code initializes the Foundry Local SDK, loads a streaming speech model, captures audio from your microphone using PyAudio, and streams it to the live transcription API. Partial results appear as you speak, and final results are printed on a new line.

Copy and paste the following code into app.py:

# Live Audio Transcription — Foundry Local SDK Example (Python)
#
# Tries PyAudio mic capture first; falls back to synthetic PCM if unavailable.
#
# Usage:
#   pip install -r requirements.txt
#   python src/app.py              # Live microphone
#   python src/app.py --synth      # Synthetic 440Hz sine wave

import math
import signal
import struct
import sys
import threading
import time

from foundry_local_sdk import (
    AudioItem,
    AudioSession,
    BytesItem,
    Configuration,
    FoundryLocalManager,
    ItemQueue,
    Request,
    SpeechResultItem,
    SpeechSegmentItem,
    SpeechSegmentKind,
)

RATE = 16000
CHANNELS = 1
CHUNK = RATE // 10


def main():
    use_synth = "--synth" in sys.argv

    print("===========================================================")
    print("   Foundry Local -- Live Audio Transcription Demo (Python)")
    print("===========================================================")
    print()

    config = Configuration(app_name="foundry_local_samples")
    FoundryLocalManager.initialize(config)
    manager = FoundryLocalManager.instance

    # English-only:
    model_alias = "nemotron-speech-streaming-en-0.6b"
    # Multi-lingual (supports 30+ languages including auto-detect):
    # model_alias = "nvidia-nemotron-3.5-asr-streaming-multilingual-0.6b"
    model = manager.catalog.get_model(model_alias)
    if model is None:
        manager.close()
        raise RuntimeError(f'Model "{model_alias}" not found in catalog')

    if not model.is_cached:
        model.download(
            lambda progress: print(
                f"\rDownloading model: {progress:.2f}%", end="", flush=True
            )
        )
        print()

    print(f"Loading model {model.id}...", end="")
    model.load()
    print("done.")

    stop_event = threading.Event()
    audio_interface = None
    audio_stream = None
    mic_active = False

    if not use_synth:
        try:
            import pyaudio

            audio_interface = pyaudio.PyAudio()
            audio_stream = audio_interface.open(
                format=pyaudio.paInt16,
                channels=CHANNELS,
                rate=RATE,
                input=True,
                frames_per_buffer=CHUNK,
            )
            mic_active = True
        except Exception as error:
            print(f"Could not initialize microphone: {error}")
            print("Falling back to synthetic audio test...\n")
            if audio_stream:
                audio_stream.close()
            if audio_interface:
                audio_interface.terminate()
            audio_interface = None
            audio_stream = None

    def request_stop(*_args):
        stop_event.set()

    signal.signal(signal.SIGINT, request_stop)

    def produce_audio(queue):
        try:
            if mic_active:
                print("===========================================================")
                print("  LIVE TRANSCRIPTION ACTIVE")
                print("  Speak into your microphone.")
                print("  Press Ctrl+C to stop.")
                print("===========================================================\n")
                while not stop_event.is_set():
                    pcm_data = audio_stream.read(CHUNK, exception_on_overflow=False)
                    if pcm_data:
                        queue.push(BytesItem(pcm_data))
            else:
                print("Pushing synthetic audio (440Hz sine, 2s)...")
                total_samples = RATE * 2
                pcm_bytes = bytearray(total_samples * 2)
                for index in range(total_samples):
                    timestamp = index / RATE
                    sample = int(32767 * 0.5 * math.sin(2 * math.pi * 440 * timestamp))
                    struct.pack_into("<h", pcm_bytes, index * 2, sample)

                chunk_size = CHUNK * 2
                for offset in range(0, len(pcm_bytes), chunk_size):
                    if stop_event.is_set():
                        break
                    queue.push(BytesItem(pcm_bytes[offset : offset + chunk_size]))
                    time.sleep(0.1)
                print("✓ Synthetic audio pushed")
        finally:
            queue.mark_finished()

    try:
        with (
            AudioSession(model) as session,
            ItemQueue() as audio_queue,
            Request() as request,
        ):
            request.add_item(
                AudioItem.create_format_descriptor(
                    "pcm", sample_rate=RATE, channels=CHANNELS
                ),
                transfer_ownership=True,
            )
            request.add_item(audio_queue, transfer_ownership=False)
            session.set_streaming(True)

            producer = threading.Thread(
                target=produce_audio, args=(audio_queue,), daemon=True
            )
            producer.start()

            print("✓ Session started")
            with session.process_streaming_request(request) as stream:
                for item in stream:
                    if isinstance(item, SpeechSegmentItem):
                        if item.kind == SpeechSegmentKind.FINAL:
                            print(f"\n  [FINAL] {item.text}")
                        elif item.text:
                            print(item.text, end="", flush=True)

                with stream.final_response as final_response:
                    result = next(
                        (
                            item
                            for item in final_response
                            if isinstance(item, SpeechResultItem)
                        ),
                        None,
                    )
                    if result is not None and result.text:
                        print(f"\nTranscript: {result.text}")

            producer.join(timeout=5)
    finally:
        stop_event.set()
        if audio_stream:
            audio_stream.stop_stream()
            audio_stream.close()
        if audio_interface:
            audio_interface.terminate()
        if model.is_loaded:
            model.unload()
        manager.close()
        print("✓ Done")


if __name__ == "__main__":
    main()

The create_live_transcription_session method returns a session that accepts raw PCM audio and yields transcription results as you stream chunks. PyAudio captures microphone audio at 16 kHz mono 16-bit — the format the session expects.

Run the application:

python src/app.py

Speak into your microphone. You see real-time transcription output:

Listening... (press Ctrl+C to stop)
Hello, this is a test of the live transcription feature.
It transcribes audio from the microphone in real time.

Press Ctrl+C to stop recording. The model finishes processing any remaining audio and the application exits.

Prerequisites

  • Rust and Cargo installed (Rust 1.70.0 or later).
  • A working microphone connected to your computer.

Samples repository

The complete sample code for this article is available in the foundry-samples GitHub repository. To clone the repository and navigate to the sample use:

git clone https://github.com/microsoft-foundry/foundry-samples.git
cd foundry-samples/samples/rust/foundry-local/live-audio-transcription-example

Install packages

cargo add foundry-local-sdk
cargo add tokio --features full
cargo add tokio-stream anyhow

The sample uses the cpal crate for cross-platform microphone capture. The dependency is already listed in Cargo.toml.

Live transcribe from microphone

The following code initializes the Foundry Local SDK, loads a streaming speech model, captures audio from your microphone using cpal, and streams it to the live transcription API. Partial results appear as you speak, and final results are printed on a new line.

Replace the contents of src/main.rs with the following code:

// Live Audio Transcription — Foundry Local Rust SDK Example
//
// Tries CPAL mic capture first; falls back to synthetic PCM if unavailable.
//
// Usage:
//   cargo run                  # Live microphone (press Ctrl+C to stop)
//   cargo run -- --synth       # Synthetic 440Hz sine wave

use std::env;
use std::io::{self, Write};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;

use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
use foundry_local_sdk::{
    AudioSession, FoundryLocalConfig, FoundryLocalManager, Item, ItemQueue, Request, TextKind,
};
use tokio_stream::StreamExt;

// English-only:
const ALIAS: &str = "nemotron-speech-streaming-en-0.6b";
// Multi-lingual (supports 30+ languages including auto-detect):
// const ALIAS: &str = "nvidia-nemotron-3.5-asr-streaming-multilingual-0.6b";

// Global flag for Ctrl+C graceful shutdown (mirrors JS process.on('SIGINT'))
static RUNNING: AtomicBool = AtomicBool::new(true);

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let use_synth = env::args().any(|a| a == "--synth");

    // Install Ctrl+C handler (mirrors JS SIGINT / C++ SignalHandler)
    let running = Arc::new(AtomicBool::new(true));
    let running_for_signal = running.clone();
    ctrlc::set_handler(move || {
        RUNNING.store(false, Ordering::SeqCst);
        running_for_signal.store(false, Ordering::SeqCst);
    })?;

    println!("===========================================================");
    println!("   Foundry Local -- Live Audio Transcription Demo (Rust)");
    println!("===========================================================");
    println!();

    let manager = FoundryLocalManager::create(FoundryLocalConfig::new("foundry_local_samples"))?;
    let model = manager.catalog().get_model(ALIAS).await?;
    println!("Model: {} (id: {})", model.alias(), model.id());

    if !model.is_cached().await? {
        println!("Downloading model...");
        model
            .download(Some(|progress: f64| {
                print!("\r  {progress:.1}%");
                io::stdout().flush().ok();
            }))
            .await?;
        println!();
    }

    println!("Loading model...");
    model.load().await?;
    println!("✓ Model loaded\n");

    let session = AudioSession::new(&model).await?;
    let audio_queue = session.create_input_queue()?;
    let mut stream = session.process_streaming_request(
        Request::new()
            .with_item(Item::audio_data(Vec::new(), Some("pcm"), 16000, 1))
            .with_input_queue(audio_queue.clone()),
    );
    println!("✓ Session started\n");

    // --- Background task reads transcription results (mirrors JS readPromise) ---
    let read_task = tokio::spawn(async move {
        while let Some(item) = stream.next().await {
            match item {
                Ok(Item::SpeechSegment(segment)) => {
                    print!("{}", segment.text);
                    io::stdout().flush().ok();
                }
                Ok(Item::Text {
                    text,
                    kind: TextKind::Default,
                }) => {
                    print!("{text}");
                    io::stdout().flush().ok();
                }
                Ok(_) => {}
                Err(e) => {
                    eprintln!("\n[ERROR] Stream error: {e}");
                    break;
                }
            }
        }
        stream.response().await
    });

    // --- Microphone capture (mirrors JS naudiodon2 / C++ PortAudio / Python PyAudio) ---
    // Try CPAL for mic input; fall back to synthetic PCM on failure.

    let mut mic_active = false;

    if !use_synth {
        match try_start_mic(&audio_queue, &running).await {
            Ok(()) => {
                mic_active = true;
            }
            Err(e) => {
                eprintln!("Could not initialize microphone: {e}");
                eprintln!("Falling back to synthetic audio test...\n");
            }
        }
    }

    // Fallback: push synthetic PCM (440Hz sine wave) — mirrors JS catch block
    if !mic_active {
        println!("Pushing synthetic audio (440Hz sine, 2s)...");
        let pcm_data = generate_sine_wave_pcm(16000, 2, 440.0);
        let chunk_size = 16000 / 10 * 2; // 100ms
        let chunk_interval = std::time::Duration::from_millis(100);
        for offset in (0..pcm_data.len()).step_by(chunk_size) {
            if !running.load(Ordering::SeqCst) {
                break;
            }
            let end = std::cmp::min(offset + chunk_size, pcm_data.len());
            audio_queue.push(&Item::bytes(pcm_data[offset..end].to_vec()))?;
            tokio::time::sleep(chunk_interval).await;
        }
        println!("✓ Synthetic audio pushed");

        // Wait for remaining transcription results
        tokio::time::sleep(std::time::Duration::from_secs(3)).await;
    }

    // Graceful shutdown (mirrors JS SIGINT handler)
    println!("\n\nStopping...");
    audio_queue.mark_finished();
    let final_response = read_task.await??;
    if let Some(result) = final_response.items.iter().find_map(Item::as_speech_result) {
        println!("Final transcript: {}", result.text);
    }
    drop(audio_queue);
    drop(session);
    model.unload().await?;
    println!("✓ Done");
    Ok(())
}

/// Try to open the default microphone with CPAL and forward PCM to the session.
/// Blocks until Ctrl+C is pressed.
async fn try_start_mic(
    audio_queue: &ItemQueue,
    running: &Arc<AtomicBool>,
) -> Result<(), Box<dyn std::error::Error>> {
    let host = cpal::default_host();
    let device = host
        .default_input_device()
        .ok_or("No input audio device available")?;
    let default_config = device.default_input_config()?;
    let device_rate = default_config.sample_rate().0;
    let device_channels = default_config.channels();
    let sample_format = default_config.sample_format();

    let mic_config = cpal::StreamConfig {
        channels: device_channels,
        sample_rate: cpal::SampleRate(device_rate),
        buffer_size: cpal::BufferSize::Default,
    };

    // Bounded channel (cap=100) mirrors JS appendQueue / C++ AudioQueue
    let (audio_tx, mut audio_rx) = tokio::sync::mpsc::channel::<Vec<u8>>(100);
    let err_fn = |err| eprintln!("Microphone stream error: {err}");

    // CPAL may deliver f32, i16, or u16 depending on the device/host. Convert
    // each supported sample format to f32 in [-1.0, 1.0] before resampling.
    let input_stream = match sample_format {
        cpal::SampleFormat::F32 => {
            let tx = audio_tx.clone();
            device.build_input_stream(
                &mic_config,
                move |data: &[f32], _: &cpal::InputCallbackInfo| {
                    let bytes = convert_audio(data, device_channels, device_rate);
                    if !bytes.is_empty() {
                        let _ = tx.try_send(bytes);
                    }
                },
                err_fn,
                None,
            )?
        }
        cpal::SampleFormat::I16 => {
            let tx = audio_tx.clone();
            device.build_input_stream(
                &mic_config,
                move |data: &[i16], _: &cpal::InputCallbackInfo| {
                    let samples: Vec<f32> =
                        data.iter().map(|&s| s as f32 / i16::MAX as f32).collect();
                    let bytes = convert_audio(&samples, device_channels, device_rate);
                    if !bytes.is_empty() {
                        let _ = tx.try_send(bytes);
                    }
                },
                err_fn,
                None,
            )?
        }
        cpal::SampleFormat::U16 => {
            let tx = audio_tx.clone();
            device.build_input_stream(
                &mic_config,
                move |data: &[u16], _: &cpal::InputCallbackInfo| {
                    let samples: Vec<f32> = data
                        .iter()
                        .map(|&s| (s as f32 / u16::MAX as f32) * 2.0 - 1.0)
                        .collect();
                    let bytes = convert_audio(&samples, device_channels, device_rate);
                    if !bytes.is_empty() {
                        let _ = tx.try_send(bytes);
                    }
                },
                err_fn,
                None,
            )?
        }
        other => {
            return Err(format!("Unsupported input sample format: {other:?}").into());
        }
    };
    drop(audio_tx);

    input_stream.play()?;

    println!("===========================================================");
    println!("  LIVE TRANSCRIPTION ACTIVE");
    println!("  Speak into your microphone.");
    println!("  Press Ctrl+C to stop.");
    println!("===========================================================");
    println!();

    // Pump audio from channel to session (mirrors JS pumpAudio / C++ pump loop)
    let queue = audio_queue.clone();
    let forward_task = tokio::spawn(async move {
        while let Some(bytes) = audio_rx.recv().await {
            if let Err(e) = queue.push(&Item::bytes(bytes)) {
                eprintln!("Append error: {e}");
                break;
            }
        }
    });

    // Block until Ctrl+C
    while running.load(Ordering::SeqCst) {
        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
    }

    drop(input_stream);
    forward_task.await?;
    Ok(())
}

fn convert_audio(data: &[f32], channels: u16, sample_rate: u32) -> Vec<u8> {
    let mono: Vec<f32> = if channels > 1 {
        data.chunks(channels as usize)
            .map(|frame| frame.iter().sum::<f32>() / channels as f32)
            .collect()
    } else {
        data.to_vec()
    };

    let resampled = if sample_rate != 16000 {
        resample(&mono, sample_rate, 16000)
    } else {
        mono
    };

    let mut bytes = Vec::with_capacity(resampled.len() * 2);
    for &s in &resampled {
        let clamped = s.clamp(-1.0, 1.0);
        let sample = (clamped * i16::MAX as f32) as i16;
        bytes.extend_from_slice(&sample.to_le_bytes());
    }
    bytes
}

fn generate_sine_wave_pcm(sample_rate: i32, duration_seconds: i32, frequency: f64) -> Vec<u8> {
    let total_samples = (sample_rate * duration_seconds) as usize;
    let mut pcm_bytes = vec![0u8; total_samples * 2];

    for i in 0..total_samples {
        let t = i as f64 / sample_rate as f64;
        let sample =
            (i16::MAX as f64 * 0.5 * (2.0 * std::f64::consts::PI * frequency * t).sin()) as i16;
        let bytes = sample.to_le_bytes();
        pcm_bytes[i * 2] = bytes[0];
        pcm_bytes[i * 2 + 1] = bytes[1];
    }

    pcm_bytes
}

fn resample(input: &[f32], from_rate: u32, to_rate: u32) -> Vec<f32> {
    if from_rate == to_rate || input.is_empty() {
        return input.to_vec();
    }

    let ratio = from_rate as f64 / to_rate as f64;
    let out_len = (input.len() as f64 / ratio).ceil() as usize;
    let mut output = Vec::with_capacity(out_len);

    for i in 0..out_len {
        let src_idx = i as f64 * ratio;
        let idx = src_idx as usize;
        let frac = src_idx - idx as f64;
        let s0 = input[idx.min(input.len() - 1)];
        let s1 = input[(idx + 1).min(input.len() - 1)];
        output.push(s0 + (s1 - s0) * frac as f32);
    }

    output
}

The create_live_transcription_session method returns a session that accepts raw Pulse-code modulation (PCM) audio and yields transcription results as an async stream. The cpal input stream captures microphone audio at 16-kHz mono, which is the format the session expects.

Run the application:

cargo run

Speak into your microphone. You see real-time transcription output:

Listening... (press Ctrl+C to stop)
Hello, this is a test of the live transcription feature.
It transcribes audio from the microphone in real time.

Press Ctrl+C to stop recording. The model finishes processing any remaining audio and the application exits.

Prerequisites

  • CMake 3.20 or later.
  • A C++20 compiler.
  • The NuGet CLI.
  • A raw, headerless 16-kHz, 16-bit, mono PCM file or a platform audio capture tool that can write this format to standard output.

Samples repository

Clone the Foundry samples GitHub repository and go to the C++ sample:

git clone https://github.com/microsoft-foundry/foundry-samples.git
cd foundry-samples/samples/cpp/foundry-local/live-audio-transcription

Install packages

The C++ samples require:

Configure and build the sample:

cmake -S . -B build
cmake --build build --config Release

During configuration, the sample restores version 2.2.1 of the Microsoft.AI.Foundry.Local.Runtime NuGet package to build/_packages. The package contains the C++ headers and native libraries for Windows, Linux, and macOS. You don't need a separate WinML package.

The CMake configuration selects the runtime assets for your operating system and architecture and copies the required native libraries beside the executable. On macOS and Linux, run the executable from build. On Windows, run the .exe file from build.

Live transcribe audio

The sample loads a streaming speech model, accepts raw PCM audio from a file or standard input, and prints partial and final transcription results.

#include <foundry_local/foundry_local_cpp.h>

#include <algorithm>
#include <cerrno>
#include <chrono>
#include <cstring>
#include <cstdint>
#include <exception>
#include <fstream>
#include <iostream>
#include <limits>
#include <stop_token>
#include <string>
#include <system_error>
#include <thread>
#include <vector>

#ifdef _WIN32
#define NOMINMAX
#include <Windows.h>
#include <fcntl.h>
#include <io.h>
#else
#include <sys/select.h>
#include <unistd.h>
#endif

using namespace foundry_local;

std::streamsize ReadStdinChunk(
    std::stop_token stop_token, std::uint8_t* data, std::size_t size) {
  while (!stop_token.stop_requested()) {
#ifdef _WIN32
    const HANDLE stdin_handle = GetStdHandle(STD_INPUT_HANDLE);
    if (stdin_handle == INVALID_HANDLE_VALUE || stdin_handle == nullptr) {
      throw std::system_error(
          static_cast<int>(GetLastError()), std::system_category(), "Could not access stdin");
    }

    DWORD available = static_cast<DWORD>(
        std::min(size, static_cast<std::size_t>(std::numeric_limits<DWORD>::max())));
    const DWORD file_type = GetFileType(stdin_handle);
    if (file_type == FILE_TYPE_CHAR) {
      const DWORD wait_result = WaitForSingleObject(stdin_handle, 100);
      if (wait_result == WAIT_TIMEOUT) {
        continue;
      }
      if (wait_result != WAIT_OBJECT_0) {
        throw std::system_error(
            static_cast<int>(GetLastError()), std::system_category(), "Could not wait for stdin");
      }
    } else if (file_type == FILE_TYPE_PIPE) {
      if (!PeekNamedPipe(stdin_handle, nullptr, 0, nullptr, &available, nullptr)) {
        const DWORD error = GetLastError();
        if (error == ERROR_BROKEN_PIPE) {
          return 0;
        }
        throw std::system_error(
            static_cast<int>(error), std::system_category(), "Could not inspect stdin");
      }
      if (available == 0) {
        std::this_thread::sleep_for(std::chrono::milliseconds(100));
        continue;
      }
    }

    const auto read_size = static_cast<unsigned int>(std::min(
        static_cast<std::size_t>(available),
        static_cast<std::size_t>(std::numeric_limits<unsigned int>::max())));
    const int count = _read(_fileno(stdin), data, read_size);
#else
    fd_set read_fds;
    FD_ZERO(&read_fds);
    FD_SET(STDIN_FILENO, &read_fds);
    timeval timeout{0, 100000};
    const int ready = select(STDIN_FILENO + 1, &read_fds, nullptr, nullptr, &timeout);
    if (ready == 0) {
      continue;
    }
    if (ready < 0) {
      if (errno == EINTR) {
        continue;
      }
      throw std::system_error(errno, std::generic_category(), "Could not wait for stdin");
    }

    const ssize_t count = read(STDIN_FILENO, data, size);
#endif
    if (count < 0) {
      if (errno == EINTR) {
        continue;
      }
      throw std::system_error(errno, std::generic_category(), "Could not read stdin");
    }
    return static_cast<std::streamsize>(count);
  }

  return 0;
}

void StreamPcm(
    std::istream& input, bool uses_stdin, ItemQueue& queue, std::stop_token stop_token) {
  constexpr std::size_t kBytesPer100Milliseconds = 16000 * 2 / 10;
  std::vector<std::uint8_t> buffer(kBytesPer100Milliseconds);

  while (!stop_token.stop_requested()) {
    std::streamsize count = 0;
    if (uses_stdin) {
      count = ReadStdinChunk(stop_token, buffer.data(), buffer.size());
    } else {
      input.read(
          reinterpret_cast<char*>(buffer.data()), static_cast<std::streamsize>(buffer.size()));
      count = input.gcount();
    }
    if (count <= 0) {
      break;
    }
    const auto size = static_cast<std::size_t>(count);
    auto* owned_chunk = new std::uint8_t[size];
    std::memcpy(owned_chunk, buffer.data(), size);
    queue.Push(Item::Bytes(
        FOUNDRY_LOCAL_ITEM_BYTES, owned_chunk, size,
        [](const flBytesData* data) {
          delete[] static_cast<std::uint8_t*>(data->mutable_data);
        }));
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
  }
  queue.MarkFinished();
}

int main(int argc, char* argv[]) {
  if (argc != 2) {
    std::cerr << "Usage: live-audio-transcription <raw-16khz-s16le-mono-pcm-file|->\n"
              << "Use '-' to read PCM from standard input. Microphone capture must be supplied "
                 "by a platform audio tool.\n";
    return 1;
  }

  try {
    Configuration config("foundry_local_cpp_live_audio");
    Manager manager(std::move(config));
    auto model = manager.GetCatalog().GetModel("nemotron-speech-streaming-en-0.6b");
    if (!model) {
      throw std::runtime_error(
          "Streaming speech model unavailable; support depends on platform and hardware.");
    }

    if (!model->IsCached()) {
      model->Download([](float progress) {
        std::cout << "\rDownloading model: " << static_cast<int>(progress) << "%" << std::flush;
        return 0;
      });
      std::cout << "\n";
    }
    model->Load();

    std::ifstream file;
    std::istream* input = &std::cin;
    const bool uses_stdin = std::string(argv[1]) == "-";
    if (uses_stdin) {
#ifdef _WIN32
      if (_setmode(_fileno(stdin), _O_BINARY) == -1) {
        throw std::runtime_error("Could not switch standard input to binary mode.");
      }
#endif
    } else {
      file.open(argv[1], std::ios::binary);
      if (!file) {
        throw std::runtime_error("Could not open PCM input file.");
      }
      input = &file;
    }

    {
      AudioSession session(*model);
      session.SetStreamingCallback([](Item item) {
        if (item.GetType() == FOUNDRY_LOCAL_ITEM_SPEECH_SEGMENT) {
          const auto segment = item.GetSpeechSegment();
          std::cout.write(segment.text.data(), static_cast<std::streamsize>(segment.text.size()));
          std::cout.flush();
        }
        return 0;
      });

      ItemQueue audio_queue;
      Request request;
      request.AddItem(Item::AudioFromData("pcm", nullptr, 0, 16000, 1));
      request.AddItem(audio_queue, false);

      std::exception_ptr producer_error;
      std::jthread producer([&](std::stop_token stop_token) {
        try {
          StreamPcm(*input, uses_stdin, audio_queue, stop_token);
        } catch (...) {
          producer_error = std::current_exception();
          if (!audio_queue.IsFinished()) {
            try {
              audio_queue.MarkFinished();
            } catch (const std::exception& cleanup_error) {
              std::cerr << "Could not finish the audio queue after a producer error: "
                        << cleanup_error.what() << "\n";
            } catch (...) {
              std::cerr << "Could not finish the audio queue after a producer error.\n";
            }
          }
        }
      });
      std::cout << "Transcription: ";
      Response response = session.ProcessRequest(request);
      producer.join();
      if (producer_error) {
        std::rethrow_exception(producer_error);
      }
      std::cout << "\n";

      for (const Item& item : response.GetItems()) {
        if (item.GetType() == FOUNDRY_LOCAL_ITEM_SPEECH_RESULT) {
          std::cout << "Final transcript: " << item.GetSpeechResult().text << "\n";
        }
      }
    }

    model->Unload();
    manager.Shutdown();
  } catch (const Error& error) {
    std::cerr << "Foundry Local error [" << error.Code() << "]: " << error.what() << "\n";
    return 1;
  } catch (const std::exception& error) {
    std::cerr << "Error: " << error.what() << "\n";
    return 1;
  }

  return 0;
}

Run the sample:

./build/live-audio-transcription path/to/audio.pcm

To transcribe microphone audio, use a platform capture tool to pipe 16-kHz, 16-bit, mono PCM to the sample and pass - as the input path. Foundry Local doesn't provide a portable microphone-capture layer for C++.