Transcribe recorded audio files with Foundry Local

Use Foundry Local's native audio transcription API and convert a local audio file into text. In this article, you create a console application that downloads a Whisper model, loads it, and streams transcription output.

Prerequisites

Samples repository

You can find the complete sample code for this article 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/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.

Transcribe an audio file

Copy and paste the following code into a C# file named Program.cs:

using Microsoft.AI.Foundry.Local;

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


// Initialize the singleton instance.
await FoundryLocalManager.CreateAsync(config, Utils.GetAppLogger());
var mgr = FoundryLocalManager.Instance;


// Ensure that any Execution Provider (EP) downloads run and are completed.
// Download and register all execution providers.
var currentEp = "";
await mgr.DownloadAndRegisterEpsAsync((epName, percent) =>
{
    if (epName != currentEp)
    {
        if (currentEp != "") Console.WriteLine();
        currentEp = epName;
    }
    Console.Write($"\r  {epName.PadRight(30)}  {percent,6:F1}%");
});
if (currentEp != "") Console.WriteLine();


// Get the model catalog
var catalog = await mgr.GetCatalogAsync();


// Get a model using an alias and select the CPU model variant
var model = await catalog.GetModelAsync("whisper-tiny") ?? throw new System.Exception("Model not found");
var modelVariant = model.Variants.First(v => v.Info.Runtime?.DeviceType == DeviceType.CPU);
model.SelectVariant(modelVariant);


// Download the model (the method skips download if already cached)
await model.DownloadAsync(progress =>
{
    Console.Write($"\rDownloading model: {progress:F2}%");
    if (progress >= 100f)
    {
        Console.WriteLine();
    }
});


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


// Create a native audio session and configure transcription.
using var audioSession = new AudioSession(model);
audioSession.SetOptions(new RequestOptions
{
    AdditionalOptions = new Dictionary<string, string> { ["language"] = "en" }
});
audioSession.SetStreaming(true);

// Get a transcription with streaming outputs
var audioFile = args.Length > 0 ? args[0] : Path.Combine(AppContext.BaseDirectory, "Recording.mp3");
Console.WriteLine($"Transcribing audio with streaming output: {Path.GetFileName(audioFile)}");
using var request = new Request();
request.AddItem(new AudioItem(audioFile));
await using var response = audioSession.ProcessStreamingRequestAsync(request);
await foreach (var item in response)
{
    using (item)
    {
        if (item is SpeechSegmentItem segment)
        {
            Console.Write(segment.Text);
            Console.Out.Flush();
        }
    }
}
using var finalResponse = await response.FinalResponse;

Console.WriteLine();


// Tidy up - unload the model
finalResponse.Dispose();
await response.DisposeAsync();
request.Dispose();
audioSession.Dispose();
await model.UnloadAsync();

The sample includes a Recording.mp3 file. To transcribe a different audio file, pass the file path as an argument.

dotnet run

To transcribe a custom audio file:

dotnet run -- path/to/audio.mp3

Prerequisites

  • Node.js version 20 or later installed.

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/audio-transcription-example

Install packages

npm install foundry-local-sdk openai

Transcribe an audio file

Copy and paste the following code into a JavaScript file named app.js:

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

// 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 successfully');

// Download and register all execution providers.
let currentEp = '';
await manager.downloadAndRegisterEps((epName, percent) => {
    if (epName !== currentEp) {
        if (currentEp !== '') process.stdout.write('\n');
        currentEp = epName;
    }
    process.stdout.write(`\r  ${epName.padEnd(30)}  ${percent.toFixed(1).padStart(5)}%`);
});
if (currentEp !== '') process.stdout.write('\n');

// Get the model object
const modelAlias = 'whisper-tiny'; // Using an available model from the list above
let model = await manager.catalog.getModel(modelAlias);
console.log(`Using model: ${model.id}`);

// Download the model
console.log(`\nDownloading model ${modelAlias}...`);
await model.download((progress) => {
    process.stdout.write(`\rDownloading... ${progress.toFixed(2)}%`);
});
console.log('\n✓ Model downloaded');

// Load the model
console.log(`\nLoading model ${modelAlias}...`);
await model.load();
console.log('✓ Model loaded');

// Create a native audio session
console.log('\nCreating audio session...');
const audioSession = new AudioSession(model);
console.log('✓ Audio session created');

// Example audio transcription
const audioFile = process.argv[2] || './Recording.mp3';
console.log(`\nTranscribing ${audioFile}...`);
const response = await audioSession.processRequest(
    new Request().addItem(Item.audioFromUri(audioFile))
);
const transcription = response.output.find((item) => item.type === 'speechResult');

console.log('\nAudio transcription result:');
console.log(transcription?.text ?? 'No transcription returned.');
console.log('✓ Audio transcription completed');

// Same example but with streaming transcription using async iteration
console.log('\nTesting streaming audio transcription...');
const stream = audioSession.processStreamingRequest(
    new Request().addItem(Item.audioFromUri(audioFile))
);
for await (const item of stream) {
    if (item.type === 'speechSegment' && item.text) {
        process.stdout.write(item.text);
    }
}
await stream.response;
console.log('\n✓ Streaming transcription completed');

// Unload the model
console.log('Unloading model...');
audioSession.dispose();
await model.unload();
console.log(`✓ Model unloaded`);

The sample includes a Recording.mp3 file. To transcribe a different audio file, pass the file path as an argument.

To run the application, use the following command in your terminal:

node app.js

To transcribe a custom audio file:

node app.js path/to/audio.mp3

Prerequisites

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/audio-transcription

Install packages

pip install foundry-local-sdk openai

Transcribe an audio file

Copy and paste the following code into a Python file named app.py:

import sys
from pathlib import Path

from foundry_local_sdk import (
    AudioItem,
    AudioSession,
    Configuration,
    FoundryLocalManager,
    Request,
    SpeechResultItem,
    TextItem,
)



def download_if_needed(model) -> None:
    if model.is_cached:
        print(f"Using cached model {model.id}.")
        return
    model.download(
        lambda progress: print(
            f"\rDownloading model: {progress:.2f}%",
            end="",
            flush=True,
        )
    )
    print()


def response_text(response) -> str:
    parts = []
    for item in response:
        if isinstance(item, SpeechResultItem):
            parts.append(item.text)
        elif isinstance(item, TextItem):
            parts.append(item.text)
    return "".join(parts)


# Initialize the Foundry Local SDK
config = Configuration(app_name="foundry_local_samples")
FoundryLocalManager.initialize(config)
manager = FoundryLocalManager.instance

# Load the speech-to-text model from the catalog.
model = manager.catalog.get_model("whisper-tiny")
if model is None:
    raise RuntimeError("Model 'whisper-tiny' was not found in the catalog.")

download_if_needed(model)
model.load()
print("Model loaded.")

try:
    # Create a native audio session and transcribe the file.
    audio_file = Path(sys.argv[1] if len(sys.argv) > 1 else "Recording.mp3")
    with AudioSession(model) as session:
        with Request().add_item(AudioItem.from_uri(str(audio_file))) as request:
            with session.process_request(request) as response:
                print("Transcription:")
                print(response_text(response))
finally:
    # Clean up
    if model.is_loaded:
        model.unload()
    manager.close()

The sample includes a Recording.mp3 file. To transcribe a different audio file, pass the file path as an argument.

Run the code by using the following command:

python app.py

To transcribe a custom audio file:

python app.py path/to/audio.mp3

Prerequisites

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/audio-transcription-example

Install packages

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

Transcribe an audio file

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

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

use std::env;
use std::io::{self, Write};
use std::path::Path;

use foundry_local_sdk::{
    AudioSession, FoundryLocalConfig, FoundryLocalManager, Item, Request, TextKind,
};
use tokio_stream::StreamExt;
use url::Url;

const ALIAS: &str = "whisper-tiny";

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    println!("Audio Transcription Example");
    println!("===========================\n");

    let audio_path = env::args()
        .nth(1)
        .unwrap_or_else(|| "Recording.mp3".to_string());

    // ── 1. Initialise the manager ────────────────────────────────────────
    let manager = FoundryLocalManager::create(FoundryLocalConfig::new("foundry_local_samples"))?;

    manager
        .download_and_register_eps_with_progress(None, {
            let mut current_ep = String::new();
            move |ep_name: &str, percent: f64| {
                if ep_name != current_ep {
                    if !current_ep.is_empty() {
                        println!();
                    }
                    current_ep = ep_name.to_string();
                }
                print!("\r  {ep_name:<30}  {percent:5.1}%");
                io::stdout().flush().ok();
            }
        })
        .await?;
    println!();

    // ── 2. Pick the Whisper model and ensure it is downloaded ───────────
    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");

    // ── 3. Create an audio session ──────────────────────────────────────
    let session = AudioSession::new(&model).await?;
    let format = Path::new(&audio_path)
        .extension()
        .and_then(|extension| extension.to_str())
        .unwrap_or("mp3")
        .to_string();
    let canonical_path = std::fs::canonicalize(&audio_path)?;
    let audio_uri = Url::from_file_path(&canonical_path).map_err(|_| {
        format!(
            "Could not convert {} to a file URI.",
            canonical_path.display()
        )
    })?;
    let audio = Item::audio_uri(audio_uri.as_str(), Some(format), 0, 0);

    // ── 4. Non-streaming transcription ──────────────────────────────────
    println!("--- Non-streaming transcription ---");
    let result = session.transcribe(audio.clone()).await?;
    println!("Transcription: {result}");

    // ── 5. Streaming transcription ──────────────────────────────────────
    println!("--- Streaming transcription ---");
    print!("Transcription: ");
    let mut stream = session.process_streaming_request(Request::from_items(vec![audio]));
    while let Some(item) = stream.next().await {
        match item? {
            Item::SpeechSegment(segment) => print!("{}", segment.text),
            Item::Text {
                text,
                kind: TextKind::Default,
            } => print!("{text}"),
            _ => {}
        }
        io::stdout().flush().ok();
    }
    let final_response = stream.response().await?;
    if let Some(result) = final_response.items.iter().find_map(Item::as_speech_result) {
        println!("\nFinal transcript: {}", result.text);
    }
    println!("\n");

    // ── 6. Unload the model ─────────────────────────────────────────────
    drop(session);
    println!("Unloading model...");
    model.unload().await?;
    println!("Done.");

    Ok(())
}

The sample includes a Recording.mp3 file. To transcribe a different audio file, pass the file path as an argument.

Run the code by using the following command:

cargo run

To transcribe a custom audio file:

cargo run -- path/to/audio.mp3

Prerequisites

  • CMake 3.20 or later.
  • A C++20 compiler.
  • The NuGet CLI.
  • An audio file to transcribe.

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/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.

Transcribe an audio file

The sample loads a speech model and streams the transcription of a local audio file.

#include <foundry_local/foundry_local_cpp.h>

#include <cstdlib>
#include <iostream>
#include <memory>
#include <string>

using namespace foundry_local;

void DownloadIfNeeded(IModel& model) {
  if (model.IsCached()) {
    std::cout << "Using cached model " << model.GetInfo().Id() << ".\n";
    return;
  }

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

void PrintTranscript(const Response& response) {
  for (const Item& item : response.GetItems()) {
    if (item.GetType() == FOUNDRY_LOCAL_ITEM_SPEECH_RESULT) {
      std::cout << item.GetSpeechResult().text << "\n";
    } else if (item.GetType() == FOUNDRY_LOCAL_ITEM_TEXT) {
      std::cout << item.GetText().text << "\n";
    }
  }
}

int main(int argc, char* argv[]) {
  if (argc != 2) {
    std::cerr << "Usage: audio-transcription <audio-file>\n";
    return 1;
  }

  try {
    Configuration config("foundry_local_cpp_audio_transcription");
    if (const char* cache_dir = std::getenv("FOUNDRY_LOCAL_SAMPLE_CACHE_DIR")) {
      config.SetModelCacheDir(cache_dir);
    }
    Manager manager(std::move(config));

    auto model = manager.GetCatalog().GetModel("whisper-tiny");
    if (!model) {
      throw std::runtime_error("Model 'whisper-tiny' was not found in the catalog.");
    }

    DownloadIfNeeded(*model);
    model->Load();

    {
      AudioSession session(*model);
      Request request{Item::AudioFromUri(argv[1])};
      Response response = session.ProcessRequest(request);
      std::cout << "Transcription:\n";
      PrintTranscript(response);
    }

    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 from the build output directory. Pass an audio file path to transcribe your own recording:

./build/audio-transcription path/to/audio.wav