ondeviceasr

package
v0.6.21 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 4, 2026 License: MIT Imports: 18 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Rendered for darwin/amd64

Overview

Package ondeviceasr provides zero-cgo on-device speech recognition on macOS using Apple's Speech framework (speech.SFSpeechRecognizer), avfaudio PCM buffers, and x/duplexaudio barge-in voice control.

The package is organized around four pieces:

Zero values of Recognizer, Session, and BargeInController are not usable; construct them with NewRecognizer, Recognizer.StartStream, and NewBargeInController.

Basic usage:

caps := ondeviceasr.Probe("en-US")
if caps.AuthStatus != ondeviceasr.AuthAuthorized || !caps.SupportsOnDevice {
	log.Printf("speech unavailable: auth=%s on_device=%v", caps.AuthStatus, caps.SupportsOnDevice)
	return
}
rec, err := ondeviceasr.NewRecognizer("en-US", nil)
if err != nil {
	log.Fatal(err)
}
defer rec.Close()

ev, err := rec.TranscribeFile(ctx, "utterance.wav")
if err != nil {
	log.Fatal(err)
}
fmt.Println(ev.Text)
Example
package main

import (
	"fmt"

	"github.com/tmc/apple/x/ondeviceasr"
)

func main() {
	caps := ondeviceasr.Probe("en-US")
	fmt.Printf("locale=%s supported_locales=%v\n", caps.Locale, len(caps.SupportedLocales) > 0)
}
Output:
locale=en-US supported_locales=true

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrUnsupportedLocale is returned when SFSpeechRecognizer cannot be
	// initialized for the requested locale.
	ErrUnsupportedLocale = errors.New("ondeviceasr: unsupported locale")
	// ErrNotAuthorized is returned when Speech Recognition TCC authorization
	// is not AuthAuthorized.
	ErrNotAuthorized = errors.New("ondeviceasr: speech recognition not authorized")
	// ErrUnavailable is returned when SFSpeechRecognizer.isAvailable is false.
	ErrUnavailable = errors.New("ondeviceasr: speech recognizer unavailable")
	// ErrOnDeviceUnsupported is returned when RequiresOnDevice is true but the
	// recognizer reports supportsOnDeviceRecognition == false.
	ErrOnDeviceUnsupported = errors.New("ondeviceasr: on-device recognition unsupported for locale")
	// ErrClosed is returned when an operation is attempted on a closed
	// Recognizer or Session.
	ErrClosed = errors.New("ondeviceasr: closed")
	// ErrEmptyAudio is returned when an empty audio slice or buffer is passed.
	ErrEmptyAudio = errors.New("ondeviceasr: empty audio")
)

Functions

func Float32FromPCMBuffer

func Float32FromPCMBuffer(buf avfaudio.AVAudioPCMBuffer) ([]float32, float64, error)

Float32FromPCMBuffer extracts mono channel-0 float32 samples and sample rate from an avfaudio.AVAudioPCMBuffer.

func PCMBufferFromFloat32

func PCMBufferFromFloat32(samples []float32, sampleRate float64) (avfaudio.AVAudioPCMBuffer, error)

PCMBufferFromFloat32 allocates a mono float32 avfaudio.AVAudioPCMBuffer at sampleRate Hz and copies samples into channel 0. The caller owns the returned Objective-C object and should call Release when finished with it.

Example
package main

import (
	"fmt"

	"github.com/tmc/apple/x/ondeviceasr"
)

func main() {
	samples := []float32{0.0, 0.25, 0.5, -0.5}
	buf, err := ondeviceasr.PCMBufferFromFloat32(samples, 16000)
	if err != nil {
		panic(err)
	}
	defer buf.Release()

	got, rate, err := ondeviceasr.Float32FromPCMBuffer(buf)
	if err != nil {
		panic(err)
	}
	fmt.Printf("frames=%d rate=%.0f first=%.2f last=%.2f\n", len(got), rate, got[0], got[len(got)-1])
}
Output:
frames=4 rate=16000 first=0.00 last=-0.50

func RMS

func RMS(samples []float32) float32

RMS returns the root-mean-square amplitude of samples.

func ReadPCM16WAV

func ReadPCM16WAV(path string) ([]float32, int, error)

ReadPCM16WAV reads a 16-bit signed PCM RIFF/WAVE file and returns mono float32 samples in [-1, 1] along with its sample rate in Hz. Multi-channel WAV inputs are downmixed to mono by averaging channels per frame.

func ResampleLinear

func ResampleLinear(samples []float32, srcRate, dstRate int) []float32

ResampleLinear resamples mono float32 audio from srcRate Hz to dstRate Hz using linear interpolation. If srcRate == dstRate or samples is empty, a copy of samples is returned.

func SupportedLocales

func SupportedLocales() []string

SupportedLocales returns the sorted list of locale identifiers supported by SFSpeechRecognizer on this host.

func WritePCM16WAV

func WritePCM16WAV(path string, sampleRate int, samples []float32) error

WritePCM16WAV writes mono float32 samples in [-1, 1] to path as a standard 16-bit signed little-endian PCM RIFF/WAVE file.

Example
package main

import (
	"fmt"
	"os"
	"path/filepath"

	"github.com/tmc/apple/x/ondeviceasr"
)

func main() {
	dir, err := os.MkdirTemp("", "ondeviceasr-example-*")
	if err != nil {
		panic(err)
	}
	defer os.RemoveAll(dir)

	wavPath := filepath.Join(dir, "clip.wav")
	in := []float32{0.0, 0.5, -0.5, 0.25}
	if err := ondeviceasr.WritePCM16WAV(wavPath, 16000, in); err != nil {
		panic(err)
	}
	out, rate, err := ondeviceasr.ReadPCM16WAV(wavPath)
	if err != nil {
		panic(err)
	}
	fmt.Printf("rate=%d frames=%d sample1=%.2f\n", rate, len(out), out[1])
}
Output:
rate=16000 frames=4 sample1=0.50

Types

type AuthStatus

type AuthStatus int

AuthStatus reports the macOS Speech Recognition TCC authorization state without triggering an interactive permission prompt.

const (
	AuthNotDetermined AuthStatus = iota
	AuthDenied
	AuthRestricted
	AuthAuthorized
)

func AuthorizationStatus

func AuthorizationStatus() AuthStatus

AuthorizationStatus returns the current Speech Recognition TCC authorization status without triggering a system permission modal.

func (AuthStatus) String

func (s AuthStatus) String() string

String returns a human-readable name for s.

type BargeInConfig

type BargeInConfig struct {
	// Keywords are case-insensitive command phrases (for example "stop",
	// "cancel", "wait") that immediately flush playback when matched in a
	// partial or final TranscriptEvent.
	Keywords []string
	// EnergyThreshold is an optional RMS amplitude threshold in [0, 1] for
	// immediate voice-activity barge-in before ASR produces a partial word.
	// A zero or negative value disables energy-based barge-in.
	EnergyThreshold float32
	// Cooldown is the minimum time between consecutive barge-in triggers.
	// Defaults to 250ms when <= 0.
	Cooldown time.Duration
}

BargeInConfig configures voice-driven barge-in cancellation on a duplexaudio.Engine.

type BargeInController

type BargeInController struct {
	// contains filtered or unexported fields
}

BargeInController connects streaming TranscriptEvent updates and captured float32 audio chunks to duplexaudio.Engine.BargeIn.

The zero value is not usable; create one with NewBargeInController.

Example
package main

import (
	"fmt"

	"github.com/tmc/apple/x/duplexaudio"
	"github.com/tmc/apple/x/ondeviceasr"
)

func main() {
	eng, err := duplexaudio.NewEngine(duplexaudio.Config{
		SampleRate: 16000,
		Channels:   1,
		FrameSize:  128,
		Mode:       duplexaudio.ModeLoopback,
	})
	if err != nil {
		panic(err)
	}
	defer eng.Close()

	eng.WritePlayback([]float32{0.5, 0.5, 0.5, 0.5})
	ctrl := ondeviceasr.NewBargeInController(eng, ondeviceasr.BargeInConfig{
		Keywords: []string{"stop", "cancel"},
	})

	ev, triggered := ctrl.HandleTranscript(ondeviceasr.TranscriptEvent{
		Text:  "please stop talking now",
		Final: false,
	})
	fmt.Printf("triggered=%v reason=%s keyword=%s queued_after=%d\n",
		triggered, ev.Reason, ev.Keyword, eng.PlaybackRing().Available())
}
Output:
triggered=true reason=keyword keyword=stop queued_after=0

func NewBargeInController

func NewBargeInController(eng *duplexaudio.Engine, cfg BargeInConfig) *BargeInController

NewBargeInController constructs a BargeInController wired to eng.

func (*BargeInController) FeedCapture

func (c *BargeInController) FeedCapture(ctx context.Context, chunkSize int, onBargeIn func(BargeInEvent), dst func([]float32) error) error

FeedCapture drains captured float32 chunks from the attached duplexaudio.Engine until ctx is cancelled, checking energy barge-in on each non-empty chunk and forwarding the chunk to dst (for example Session.WriteFloat32).

func (*BargeInController) HandleAudio

func (c *BargeInController) HandleAudio(samples []float32) (BargeInEvent, bool)

HandleAudio evaluates the RMS energy of samples and triggers duplexaudio.Engine.BargeIn when BargeInConfig.EnergyThreshold is met.

func (*BargeInController) HandleTranscript

func (c *BargeInController) HandleTranscript(ev TranscriptEvent) (BargeInEvent, bool)

HandleTranscript inspects ev.Text for any configured barge-in keyword. When a keyword matches (and the cooldown has elapsed), it invokes duplexaudio.Engine.BargeIn and returns the resulting BargeInEvent.

func (*BargeInController) TriggerCount

func (c *BargeInController) TriggerCount() uint64

TriggerCount returns the total number of barge-in flushes triggered by c.

type BargeInEvent

type BargeInEvent struct {
	// Reason is "keyword" or "energy".
	Reason       string
	Keyword      string
	Transcript   string
	FlushLatency time.Duration
	RMS          float32
}

BargeInEvent describes a triggered playback flush-to-silence event.

type Capabilities

type Capabilities struct {
	// Locale is the resolved locale identifier (for example "en-US").
	Locale string
	// Available reports SFSpeechRecognizer.isAvailable.
	Available bool
	// SupportsOnDevice reports SFSpeechRecognizer.supportsOnDeviceRecognition.
	SupportsOnDevice bool
	// AuthStatus reports SFSpeechRecognizer.authorizationStatus without prompting.
	AuthStatus AuthStatus
	// SupportedLocales is the sorted list of locale identifiers supported by
	// SFSpeechRecognizer on this host.
	SupportedLocales []string
	// NativeSampleRate is the preferred sample rate reported by
	// SFSpeechAudioBufferRecognitionRequest.nativeAudioFormat, or 0 if unavailable.
	NativeSampleRate float64
}

Capabilities describes the Speech framework capabilities for a locale on the current host.

func Probe

func Probe(locale string) Capabilities

Probe inspects SFSpeechRecognizer capabilities for locale without prompting for TCC permission. If locale is empty, the system default locale is probed.

type Options

type Options struct {
	// RequiresOnDevice forces recognition to stay completely on-device without
	// sending audio over the network.
	RequiresOnDevice bool
	// PartialResults enables intermediate hypothesis callbacks during streaming.
	PartialResults bool
	// AddsPunctuation asks Speech to insert punctuation in recognized text.
	AddsPunctuation bool
	// TaskHint guides the language model (for example TaskHintDictation).
	TaskHint TaskHint
	// ContextualStrings biases recognition toward domain-specific words or
	// commands (Apple recommends <= 100 short phrases).
	ContextualStrings []string
}

Options configures a Recognizer.

func DefaultOptions

func DefaultOptions() Options

DefaultOptions returns recommended defaults for low-latency on-device dictation and voice control.

type Recognizer

type Recognizer struct {
	// contains filtered or unexported fields
}

Recognizer wraps Apple's speech.SFSpeechRecognizer on a background foundation.OperationQueue for zero-cgo file and streaming speech recognition.

The zero value is not usable; create one with NewRecognizer.

func NewRecognizer

func NewRecognizer(locale string, opts *Options) (*Recognizer, error)

NewRecognizer creates a Recognizer for locale (for example "en-US"; empty selects the system default locale). If opts is nil, DefaultOptions is used.

NewRecognizer does not prompt for TCC authorization; authorization is checked when Recognizer.TranscribeFile or Recognizer.StartStream is called.

func (*Recognizer) Capabilities

func (r *Recognizer) Capabilities() Capabilities

Capabilities reports the current availability, on-device support, and TCC authorization status of r without prompting.

func (*Recognizer) Close

func (r *Recognizer) Close() error

Close releases the underlying speech.SFSpeechRecognizer and queue.

func (*Recognizer) Locale

func (r *Recognizer) Locale() string

Locale returns the resolved locale identifier of r.

func (*Recognizer) Options

func (r *Recognizer) Options() Options

Options returns a copy of the recognizer's configuration.

func (*Recognizer) StartStream

func (r *Recognizer) StartStream(ctx context.Context, sampleRate float64) (*Session, error)

StartStream begins a live streaming recognition Session expecting mono float32 PCM audio at sampleRate Hz (for example 16000, 24000, or 48000).

func (*Recognizer) TranscribeFile

func (r *Recognizer) TranscribeFile(ctx context.Context, audioPath string) (TranscriptEvent, error)

TranscribeFile transcribes an audio file (WAV, AIFF, CAF, M4A) using speech.SFSpeechURLRecognitionRequest and returns the final TranscriptEvent.

type Segment

type Segment struct {
	Text         string
	Confidence   float32
	Timestamp    time.Duration
	Duration     time.Duration
	Alternatives []string
}

Segment is a single timed utterance segment from speech.SFTranscriptionSegment.

type Session

type Session struct {
	// contains filtered or unexported fields
}

Session represents an active streaming speech recognition task backed by speech.SFSpeechAudioBufferRecognitionRequest.

Call Session.WriteFloat32 or Session.WritePCMBuffer to append audio, read partial and final results from Session.Events, call Session.EndAudio when input finishes, and always call Session.Close to release resources.

func (*Session) Close

func (s *Session) Close() error

Close ends audio input, cancels the recognition task if still active, and releases Objective-C resources. Close is idempotent.

func (*Session) EndAudio

func (s *Session) EndAudio() error

EndAudio signals that no more audio will be written to the session so the recognizer can emit a final TranscriptEvent. EndAudio is idempotent.

func (*Session) Events

func (s *Session) Events() <-chan TranscriptEvent

Events returns the channel of partial and final TranscriptEvent updates. The channel closes once a final result, error, or Session.Close completes.

func (*Session) WriteFloat32

func (s *Session) WriteFloat32(samples []float32) error

WriteFloat32 converts mono float32 PCM samples to an avfaudio.AVAudioPCMBuffer at the session's sample rate and appends it to the recognition request.

func (*Session) WritePCMBuffer

func (s *Session) WritePCMBuffer(buf avfaudio.AVAudioPCMBuffer) error

WritePCMBuffer appends a pre-built avfaudio.AVAudioPCMBuffer directly to the underlying speech.SFSpeechAudioBufferRecognitionRequest.

type TaskHint

type TaskHint int

TaskHint hints to Apple's Speech recognizer what kind of speech is expected.

const (
	TaskHintUnspecified TaskHint = iota
	TaskHintDictation
	TaskHintSearch
	TaskHintConfirmation
)

type TranscriptEvent

type TranscriptEvent struct {
	Text     string
	Final    bool
	Segments []Segment
	Latency  time.Duration
	Err      error
}

TranscriptEvent carries a partial or final transcription update from Recognizer.TranscribeFile or Session.Events.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL