Voice Input

Let players speak to NPCs instead of typing. Voice input is optional - LoreMindNPC works without it.

Prerequisites

  • A working LoreMindNPC in your scene (see Your First NPC)
  • For the built-in engine: the whisper.unity package (com.whisper.unity)

Overview

The SDK includes built-in support for Whisper via whisper.unity, a local speech-to-text engine. You can also bring your own STT solution by implementing the ISpeechToTextProvider interface.

OptionTypeNotes
WhisperLocalFree, offline, multi-language
CustomAnyImplement ISpeechToTextProvider

Using Whisper (Built-in)

1. Install whisper.unity

  1. Open Window > Package Management > Package Manager (Unity 6000.0 and 2022.3: Window > Package Manager)
  2. Click + > Install package from git URL (Unity 2022.3: Add package from git URL)
  3. Paste: https://github.com/Macoron/whisper.unity.git?path=/Packages/com.whisper.unity#529a628a915a97799e89e061af9cb7c71407124d
  4. Click Install (Unity 2022.3: Add)

Use this exact URL. The LOREMIND_WHISPER define is set automatically when the package is installed; you don't add it to Player Settings.

Whisper Models

Download a model in Control Panel > Voice. It's placed in StreamingAssets/Whisper. If you download a model manually, use the link shown in the Control Panel.

Load only the models the Control Panel downloads. Don't let players load their own model files.

2. Enable in Project Settings

  1. Open Window > LoreMind > Control Panel
  2. Go to Voice tab
  3. Enable Speech-to-Text
  4. Set STT Provider to Whisper
  5. Optionally set Language Code (e.g., "en" for English, "auto" to detect it). It's applied to the scene's WhisperManager at startup. It's empty by default, which keeps the WhisperManager's own setting.

Quick Setup

Add the Component

  1. Create a GameObject (or use your Player)
  2. Add Component > LoreMind > Voice > Voice Input

The component auto-adds required dependencies:

  • MicrophoneInputHandler - Captures audio
  • SpeechCaptureController - Manages recording and transcription

Wire to NPC

Option A: Inspector

Set Target NPC to your LoreMindNPC component. Transcriptions automatically trigger NPC responses.

Option B: Code

csharp
voiceInput.OnTranscription.AddListener(text =>
{
    npc.Respond(text);
});

Capture Modes

Push-to-Talk (Default)

Player holds a key to record, releases to transcribe:

csharp
voiceInput.PushToTalk = true;
voiceInput.PushToTalkKey = KeyCode.V;

Input System note: KeyCode-based push-to-talk relies on the legacy Input Manager. If your project's Active Input Handling is set to Input System Package (New) only, drive capture from your own InputAction handlers by calling StartCapture() / StopCapture() directly (max-duration enforcement still applies).

Manual Mode

Control capture from code:

csharp
voiceInput.PushToTalk = false;

// Start/stop manually
voiceInput.StartCapture();
voiceInput.StopCapture();

// Or capture for a specific duration (adjust based on expected speech length)
string text = await voiceInput.CaptureAndTranscribeAsync(maxDuration);
// text is what was recognized in THIS capture, or null if nothing was

Every finished capture ends in exactly one of: OnTranscription (text recognized), OnError (nothing recognized, or speech-to-text failed), or nothing at all for recordings shorter than Min Recording Seconds (accidental taps). Voice input is ready for the next capture in every case.

StartCapture() raises OnError instead of recording when speech-to-text is off, microphone permission was denied, or the microphone isn't running yet. CancelCapture() stops and discards the audio: nothing is transcribed, and a waiting CaptureAndTranscribeAsync returns null. After the component is disabled or destroyed, a transcription still in progress delivers nothing.

Complete Example

csharp
using UnityEngine;
using UnityEngine.UI;
using Peek.LoreMind;
using Peek.LoreMind.Voice;

public class VoiceNPCDemo : MonoBehaviour
{
    [SerializeField] private LoreMindNPC npc;
    [SerializeField] private LoreMindVoiceInput voiceInput;

    [Header("UI")]
    [SerializeField] private GameObject recordingIndicator;
    [SerializeField] private Text subtitleText;

    void Start()
    {
        // Configure
        voiceInput.PushToTalk = true;
        voiceInput.PushToTalkKey = KeyCode.V;

        // Wire up events
        voiceInput.OnCaptureStarted.AddListener(() =>
        {
            recordingIndicator.SetActive(true);
            subtitleText.text = "Listening...";
        });

        voiceInput.OnCaptureStopped.AddListener(() =>
        {
            recordingIndicator.SetActive(false);
            subtitleText.text = "Processing...";
        });

        voiceInput.OnTranscription.AddListener(text =>
        {
            subtitleText.text = $"You: {text}";
            npc.Respond(text);
        });

        voiceInput.OnError.AddListener(error =>
        {
            subtitleText.text = $"Error: {error}";
            recordingIndicator.SetActive(false);
        });

        // Show NPC response
        npc.OnResponseReceived.AddListener(response =>
        {
            subtitleText.text = $"NPC: {response}";
        });
    }
}

Configuration

Capture Settings

SettingDescriptionDefault
Max Recording SecondsAuto-stop after this duration10s
Min Recording SecondsDiscard shorter recordings0.3s

Auto-Response Settings

SettingDescriptionDefault
Target NPCNPC to send transcriptions toNone
Minimum Text LengthDiscard shorter transcriptions3 chars

Events

csharp
// Capture lifecycle
voiceInput.OnCaptureStarted.AddListener(() => ShowRecordingUI());
voiceInput.OnCaptureStopped.AddListener(() => HideRecordingUI());

// Results
voiceInput.OnTranscription.AddListener(text => HandlePlayerSpeech(text));
voiceInput.OnError.AddListener(error => ShowErrorMessage(error));

API Summary

Properties

csharp
bool IsCapturing { get; }
float CaptureDuration { get; }
bool IsTranscribing { get; }
string LastTranscription { get; }

bool PushToTalk { get; set; }
KeyCode PushToTalkKey { get; set; }
LoreMindNPC TargetNPC { get; set; }

Methods

csharp
void StartCapture()
void StopCapture()
Task<string> CaptureAndTranscribeAsync(float durationSeconds = 0f)
void CancelCapture()

Audio Providers

UnityMicrophone (Default)

Uses Unity's built-in Microphone class. It's compiled into your game only when voice input can be used: when whisper.unity is installed (LOREMIND_WHISPER, automatic), or when you add the LOREMIND_MICROPHONE scripting define yourself (for example to capture audio for your own speech-to-text). Text-only games therefore never reference the Microphone class, so Unity doesn't add the Android RECORD_AUDIO permission and iOS doesn't need a microphone usage description. Not available on WebGL.

Microphone Permission (Android, iOS)

MicrophoneInputHandler asks for microphone permission just before it first starts recording. On iOS, also fill in Player Settings > Other Settings > Microphone Usage Description.

If the player denies it, voice input stays off and MicrophoneInputHandler.OnMicrophonePermissionDenied fires, so you can explain why voice needs the microphone. Recording starts automatically when the app regains focus with the permission granted (for example after the player enabled it in the system settings). Regaining focus never asks again: only RetryMicrophone() shows the permission dialog again (on Android 11 and later a second denial is final, so ask only after explaining why). MicrophoneInputHandler.IsMicrophonePermissionDenied tells you the current state. Disabling the component releases the microphone and stops a start still waiting for the dialog; enabling it starts recording again.

Custom Provider

To feed audio from another source (a VoIP SDK such as Dissonance, FMOD, Wwise, a file), implement IAudioProvider and expose it through an AudioProviderComponent, then set the handler's Provider Type to Custom Component and assign your component:

csharp
using UnityEngine;
using Peek.LoreMind.Audio;

public class MyAudioProviderComponent : AudioProviderComponent
{
    public override IAudioProvider CreateProvider(int sampleRate, int lengthSeconds)
    {
        return new MyAudioProvider();
    }
}

public class MyAudioProvider : IAudioProvider
{
    public string ProviderName => "MyProvider";
    public string DeviceName => null;
    public AudioClip AudioClip { get; private set; }
    public int SampleRate { get; private set; }
    public int Channels => 1;
    public bool IsActive { get; private set; }

    public bool Initialize(int sampleRate, int lengthSeconds) { /* ... */ }
    public bool Start() { /* ... */ }
    public void Stop() { /* ... */ }
    public int GetCurrentPosition() { /* ... */ }
    public bool GetAudioData(float[] samples, int offsetSamples) { /* ... */ }
    public void Dispose() { /* ... */ }
    public string[] GetAvailableDevices() => new string[0];
    public bool SetDevice(string deviceName) => false;
    public string GetCurrentDevice() => null;
}

Dissonance: LoreMind 1.0.9 doesn't include a ready-made Dissonance integration. Use a custom provider as shown above.

Platform Support

Voice input uses microphone capture and is not available on WebGL. All other Unity platforms with microphone access are supported.

Best Practices

Provide Visual Feedback

Always show recording and processing states:

csharp
voiceInput.OnCaptureStarted.AddListener(() => recordingIcon.SetActive(true));
voiceInput.OnCaptureStopped.AddListener(() =>
{
    recordingIcon.SetActive(false);
    processingIcon.SetActive(true);
});
voiceInput.OnTranscription.AddListener(text => processingIcon.SetActive(false));

Display Transcriptions

Show players what was heard:

csharp
voiceInput.OnTranscription.AddListener(text =>
{
    subtitleText.text = $"You: {text}";
});

Offer Both Voice and Text

csharp
// Voice input
voiceInput.OnTranscription.AddListener(SendToNPC);

// Text input
textInput.onEndEdit.AddListener(SendToNPC);

void SendToNPC(string playerInput)
{
    if (!string.IsNullOrEmpty(playerInput))
        npc.Respond(playerInput);
}

Custom STT Provider

If you prefer a different speech-to-text solution, implement the ISpeechToTextProvider interface:

csharp
using Peek.LoreMind.Services;
using System.Threading.Tasks;

public class MyCustomSTT : ISpeechToTextProvider
{
    public string ProviderName => "MyCustomSTT";
    public bool IsReady { get; private set; }

    public async Task<bool> InitializeAsync()
    {
        // Initialize your STT engine
        IsReady = true;
        return true;
    }

    public async Task<string> TranscribeAsync(
        float[] audioData,
        int sampleRate,
        int channels)
    {
        // Transcribe audio using your STT engine
        // audioData: raw float samples
        // sampleRate: typically 16000 for STT
        // channels: 1 for mono, 2 for stereo

        // Return transcribed text
        return "transcribed text";
    }

    public void Dispose()
    {
        // Clean up resources
    }
}

Troubleshooting

No microphone detected

Check microphone permissions:

  • Windows: Settings > Privacy > Microphone
  • macOS: System Preferences > Security & Privacy > Microphone
  • Android / iOS: the SDK asks for permission when voice input starts. If the player denied it, OnMicrophonePermissionDenied fires; recording starts once they allow it in the system settings and return to the game (or call RetryMicrophone()). On iOS, set Microphone Usage Description in Player Settings.

"Microphone capture is not compiled into this project"

Install whisper.unity (see Install whisper.unity), or add the LOREMIND_MICROPHONE scripting define if you use your own speech-to-text. This is an error only when Speech-to-Text is enabled in the Control Panel. In a text-only project (Speech-to-Text off), a MicrophoneInputHandler in the scene, such as the example scene's voice objects, switches itself off with a single warning (shown at the Warnings log level).

Whisper model download "rejected and deleted"

The downloaded file didn't match the expected model, so it wasn't installed. Try again; if it keeps failing, download the file manually from the link shown in the Control Panel.

Transcription returns empty

  • Verify the recording wasn't too short (below Min Recording Seconds); those captures are ignored without an error, as accidental taps
  • "No speech was recognized" means Whisper ran and heard nothing usable: speak louder or closer to the microphone
  • "Transcription failed" means Whisper couldn't run: no WhisperManager in the loaded scenes, or its model file is missing or broken (check the WhisperManager's model path and the Console)

"Speech-to-text not enabled"

Open Window > LoreMind > Control Panel > Voice and enable Speech-to-Text.

First transcription is slow

Whisper runs locally and must load its model first. The WhisperManager loads it on Awake when its Init On Awake option is on; otherwise LoreMind starts loading it when voice input starts. A transcription requested while the model is still loading waits for it. Later transcriptions are faster.

Next Steps