speech-recognition
dpearson2699/swift-ios-skills
Transcribe speech to text on iOS using Apple's Speech framework.
What is speech-recognition?
Transcribe live microphone audio or pre-recorded files to text using Apple's Speech framework. Use this skill when implementing speech-to-text recognition, handling microphone authorization, choosing between on-device (SpeechAnalyzer on iOS 26+) or server-backed (SFSpeechRecognizer) approaches, and managing audio capture with AVAudioEngine.
- Transcribe live microphone audio to text with AVAudioEngine capture
- Recognize pre-recorded audio files using SFSpeechURLRecognitionRequest
- Handle speech recognition and microphone authorization flows
- Choose between on-device SpeechAnalyzer (iOS 26+) and server-backed SFSpeechRecognizer (iOS 10+)
- Support partial and final transcription results with real-time streaming
- Configure audio session, locale selection, and availability monitoring
How to install speech-recognition
npx skills add https://github.com/dpearson2699/swift-ios-skills --skill speech-recognition- Add NSSpeechRecognitionUsageDescription and NSMicrophoneUsageDescription to Info.plist
- Request both speech recognition and microphone permissions before use
- Configure AVAudioSession with appropriate category and options
How to use speech-recognition
- 1.Request speech recognition and microphone permissions using SFSpeechRecognizer.requestAuthorization and AVAudioSession.requestRecordPermission
- 2.Create an SFSpeechRecognizer instance with desired locale or use SpeechTranscriber for iOS 26+
- 3.For live transcription: configure AVAudioEngine, create SFSpeechAudioBufferRecognitionRequest, install audio tap, and handle results in recognitionTask callback
- 4.For file transcription: create SFSpeechURLRecognitionRequest with file URL and call recognitionTask
- 5.Handle partial results (shouldReportPartialResults = true) for real-time UI updates and final results when isFinal is true
- 6.Stop transcription by removing audio tap, calling endAudio on the request, and canceling the recognition task
Use cases
- Build a live dictation or voice-note app with real-time transcription
- Transcribe recorded audio files for archival or processing
- Implement voice commands or voice-activated features in an app
- Create a multilingual transcription tool with locale selection
- Add speech-to-text to accessibility features for users with mobility limitations
- iOS app developers implementing speech-to-text features
- Accessibility engineers adding voice input capabilities
- Developers building dictation or voice-note applications
- Teams targeting iOS 10+ with fallback support or iOS 26+ with modern APIs
speech-recognition FAQ
Use SpeechAnalyzer with SpeechTranscriber or DictationTranscriber on iOS 26+ for modern on-device transcription with time-indexed results. Use SFSpeechRecognizer for iOS 10+ deployment targets, server-backed locale coverage, or existing callback-based implementations.
You must request both NSSpeechRecognitionUsageDescription (speech recognition) and NSMicrophoneUsageDescription (microphone access) in Info.plist, and call SFSpeechRecognizer.requestAuthorization and AVAudioSession.requestRecordPermission before starting transcription.
Set shouldReportPartialResults = true on your SFSpeechAudioBufferRecognitionRequest, then handle partial results in the recognitionTask callback before isFinal becomes true.
Yes, use SFSpeechURLRecognitionRequest with a file URL instead of SFSpeechAudioBufferRecognitionRequest. This works for pre-recorded audio on disk.
Use natural-language skill for text analysis, language identification, sentiment, or embeddings after transcription; use avkit for audio playback UI; use apple-on-device-ai for summarization or generation over transcripts.
Full instructions (SKILL.md)
Source of truth, from dpearson2699/swift-ios-skills.
name: speech-recognition description: "Transcribe speech to text using Apple's Speech framework. Use when implementing live microphone transcription with AVAudioEngine, recognizing recorded audio files, handling speech and microphone authorization, choosing on-device vs server-backed SFSpeechRecognizer behavior, or adopting SpeechAnalyzer, SpeechTranscriber, DictationTranscriber, AssetInventory, and async result streams on iOS 26+."
Speech Recognition
Transcribe live and pre-recorded audio to text using Apple's Speech framework.
Covers SpeechAnalyzer / SpeechTranscriber (iOS 26+) and
SFSpeechRecognizer (iOS 10+) fallback guidance.
Scope boundary: Use this skill for speech-to-text recognition, speech
authorization, microphone capture plumbing, and result handling. Hand off text
analysis, language identification after transcription, sentiment, embeddings,
and translation to natural-language; hand off audio playback UI to avkit;
hand off summarization or generation over transcripts to apple-on-device-ai.
Contents
- SpeechAnalyzer Strategy (iOS 26+)
- SFSpeechRecognizer Setup
- Authorization
- Live Microphone Transcription
- Pre-Recorded Audio File Recognition
- On-Device vs Server Recognition
- Handling Results
- Common Mistakes
- Review Checklist
- References
SpeechAnalyzer Strategy (iOS 26+)
Use SpeechAnalyzer for modern iOS 26+ speech analysis, especially long-form
recordings, live transcription, time-indexed transcripts, and fully on-device
flows. Keep SFSpeechRecognizer for iOS 10+ deployment targets, server-backed
locale coverage, or existing callback/delegate implementations.
Read SpeechAnalyzer patterns when implementing an iOS 26+ transcription pipeline, model asset handling, volatile results, or file/buffer examples.
SpeechAnalyzer setup checklist
- Choose the module:
SpeechTranscriberfor the newer general-purpose on-device model.DictationTranscriberwhenSpeechTranscriberis unavailable for the current device or locale and dictation-compatible support is acceptable.SpeechDetectoronly in conjunction with a transcriber when voice activity detection is worth the accuracy/power tradeoff.
- Check support before creating the session:
SpeechTranscriber.isAvailableSpeechTranscriber.supportedLocale(equivalentTo:)SpeechTranscriber.installedLocales/supportedLocaleswhen showing language choices.
- Pick a documented preset:
.transcriptionfor basic accurate transcription..progressiveTranscriptionfor live UI updates..timeIndexedProgressiveTranscriptionwhen playback highlighting needsaudioTimeRange.
- Install required assets with
AssetInventory.assetInstallationRequest. - Convert live audio buffers to
SpeechAnalyzer.bestAvailableAudioFormat(compatibleWith:)before yieldingAnalyzerInput. - Consume module results from their
AsyncSequencein a separate task. - Finish explicitly with
finalizeAndFinish(through:),finalizeAndFinishThroughEndOfInput(), orcancelAndFinishNow().
Do not use an offlineTranscription preset; Apple does not document one.
Finishing an AsyncStream input sequence does not finish the analyzer session.
SFSpeechRecognizer Setup
Creating a recognizer with locale
import Speech
// Default locale (user's current language)
let recognizer = SFSpeechRecognizer()
// Specific locale
let recognizer = SFSpeechRecognizer(locale: Locale(identifier: "en-US"))
// Check if recognition is available for this locale
guard let recognizer, recognizer.isAvailable else {
print("Speech recognition not available")
return
}
Monitoring availability changes
final class SpeechManager: NSObject, SFSpeechRecognizerDelegate {
private let recognizer = SFSpeechRecognizer()!
override init() {
super.init()
recognizer.delegate = self
}
func speechRecognizer(
_ speechRecognizer: SFSpeechRecognizer,
availabilityDidChange available: Bool
) {
// Update UI — disable record button when unavailable
}
}
Authorization
Request both speech recognition and microphone permissions before starting
live transcription. Add these keys to Info.plist:
NSSpeechRecognitionUsageDescriptionNSMicrophoneUsageDescription
import Speech
import AVFoundation
func requestPermissions() async -> Bool {
let speechStatus = await withCheckedContinuation { continuation in
SFSpeechRecognizer.requestAuthorization { status in
continuation.resume(returning: status)
}
}
guard speechStatus == .authorized else { return false }
let micStatus: Bool
if #available(iOS 17, *) {
micStatus = await AVAudioApplication.requestRecordPermission()
} else {
micStatus = await withCheckedContinuation { continuation in
AVAudioSession.sharedInstance().requestRecordPermission { granted in
continuation.resume(returning: granted)
}
}
}
return micStatus
}
Live Microphone Transcription
The standard pattern: AVAudioEngine captures microphone audio → buffers are
appended to SFSpeechAudioBufferRecognitionRequest → results stream in.
import Speech
import AVFoundation
final class LiveTranscriber {
private let recognizer = SFSpeechRecognizer(locale: Locale(identifier: "en-US"))!
private let audioEngine = AVAudioEngine()
private var recognitionRequest: SFSpeechAudioBufferRecognitionRequest?
private var recognitionTask: SFSpeechRecognitionTask?
func startTranscribing() throws {
// Cancel any in-progress task
recognitionTask?.cancel()
recognitionTask = nil
// Configure audio session
let audioSession = AVAudioSession.sharedInstance()
try audioSession.setCategory(.record, mode: .measurement, options: .duckOthers)
try audioSession.setActive(true, options: .notifyOthersOnDeactivation)
// Create request
let request = SFSpeechAudioBufferRecognitionRequest()
request.shouldReportPartialResults = true
self.recognitionRequest = request
// Start recognition task
recognitionTask = recognizer.recognitionTask(with: request) { result, error in
if let result {
let text = result.bestTranscription.formattedString
print("Transcription: \(text)")
if result.isFinal {
self.stopTranscribing()
}
}
if let error {
print("Recognition error: \(error)")
self.stopTranscribing()
}
}
// Install audio tap
let inputNode = audioEngine.inputNode
let recordingFormat = inputNode.outputFormat(forBus: 0)
inputNode.installTap(onBus: 0, bufferSize: 1024, format: recordingFormat) {
buffer, _ in
request.append(buffer)
}
audioEngine.prepare()
try audioEngine.start()
}
func stopTranscribing() {
audioEngine.stop()
audioEngine.inputNode.removeTap(onBus: 0)
recognitionRequest?.endAudio()
recognitionRequest = nil
recognitionTask?.cancel()
recognitionTask = nil
}
}
Pre-Recorded Audio File Recognition
Use SFSpeechURLRecognitionRequest for audio files on disk:
func transcribeFile(at url: URL) async throws -> String {
guard let recognizer = SFSpeechRecognizer(), recognizer.isAvailable else {
throw SpeechError.unavailable
}
let request = SFSpeechURLRecognitionRequest(url: url)
request.shouldReportPartialResults = false
return try await withCheckedThrowingContinuation { continuation in
var didResume = false
recognizer.recognitionTask(with: request) { result, error in
guard !didResume else { return }
if let error {
didResume = true
continuation.resume(throwing: error)
} else if let result, result.isFinal {
didResume = true
continuation.resume(
returning: result.bestTranscription.formattedString
)
}
}
}
}
On-Device vs Server Recognition
SFSpeechRecognizer can use on-device recognition for supported locales on
iOS 13+. If supportsOnDeviceRecognition is false, the recognizer requires a
network connection. requiresOnDeviceRecognition only has effect when the
recognizer supports it.
let recognizer = SFSpeechRecognizer(locale: Locale(identifier: "en-US"))!
// Check if on-device is supported for this locale
if recognizer.supportsOnDeviceRecognition {
let request = SFSpeechAudioBufferRecognitionRequest()
request.requiresOnDeviceRecognition = true // Force on-device
}
SFSpeechRecognizer requests may still be a poor fit for long-form capture.
Apple documents a roughly one-minute task limit for speech recognition and
other service limits. For long recordings on iOS 26+, prefer SpeechAnalyzer;
otherwise chunk or restart recognition before the limit and preserve transcript
state across tasks.
Handling Results
Partial vs final results
With shouldReportPartialResults, replace the displayed partial transcript until SFSpeechRecognitionResult.isFinal commits it. This is separate from SpeechTranscriber.Result.isFinal, whose volatile attributed range must be replaced by the final result for that range. The live example and references/speechanalyzer-patterns.md contain the canonical loops.
Accessing alternative transcriptions and confidence
recognizer.recognitionTask(with: request) { result, error in
guard let result else { return }
// Best transcription
let best = result.bestTranscription
// All alternatives (sorted by confidence, descending)
for transcription in result.transcriptions {
for segment in transcription.segments {
print("\(segment.substring): \(segment.confidence)")
}
}
}
Adding punctuation (iOS 16+)
let request = SFSpeechAudioBufferRecognitionRequest()
request.addsPunctuation = true
Contextual strings
Improve recognition of domain-specific terms:
let request = SFSpeechAudioBufferRecognitionRequest()
request.contextualStrings = ["SwiftUI", "Xcode", "CloudKit"]
Common Mistakes
| Mistake | Fix |
|---|---|
| Live audio requests only speech authorization | Require both speech and microphone permission. |
| Recognizer availability is checked once | Observe delegate availability changes and model loss of service. |
| Final/error/rollover paths perform different cleanup | Use one stopTranscribing() owner for engine stop, tap removal, endAudio, and task cancellation. |
| On-device mode is forced for every locale | Check supportsOnDeviceRecognition and provide a fallback. |
One SFSpeechRecognizer task is used for long-form capture | Prefer SpeechAnalyzer on iOS 26+ or roll bounded segments while preserving committed transcript. |
| Finishing analyzer input is treated as session completion | Explicitly finalize through the last sample or cancel-and-finish. |
| Volatile SpeechAnalyzer results are appended | Replace the volatile range until a final result commits it. |
| A second recognition task starts before the first ends | Cancel/finish the active task and complete cleanup before replacement. |
Load references/speechanalyzer-patterns.md for complete analyzer finalization and volatile-result code.
Review Checklist
-
NSSpeechRecognitionUsageDescriptionis in Info.plist -
NSMicrophoneUsageDescriptionis in Info.plist (if using live audio) - Authorization is requested before starting recognition
-
SFSpeechRecognizerDelegateis set to handleavailabilityDidChange - Audio engine is stopped and tap removed when recognition ends
-
recognitionRequest.endAudio()is called when done recording - Previous
recognitionTaskis canceled before starting a new one -
supportsOnDeviceRecognitionis checked before requiring on-device mode - Partial results are handled separately from final (
isFinal) results -
SFSpeechRecognizerone-minute/service limits are accounted for - For iOS 26+:
AssetInventoryassets are installed before usingSpeechAnalyzer - For iOS 26+:
SpeechTranscriber.isAvailableand locale support are checked - For iOS 26+: live buffers are converted to the analyzer-compatible format
- For iOS 26+: analyzer sessions are explicitly finalized or canceled
- For iOS 26+: volatile results are replaced by finalized results, not duplicated
References
- Speech framework
- SpeechAnalyzer
- SpeechTranscriber
- SpeechTranscriber.Preset
- DictationTranscriber
- SpeechDetector
- SFSpeechRecognizer
- SFSpeechAudioBufferRecognitionRequest
- SFSpeechURLRecognitionRequest
- SFSpeechRecognitionResult
- SFSpeechRecognitionRequest
- AssetInventory
- Asking Permission to Use Speech Recognition
- Recognizing Speech in Live Audio
- Bring advanced speech-to-text to your app with SpeechAnalyzer
Related skills
More from dpearson2699/swift-ios-skills and the wider catalog.

spritekit
Build 2D games and animations with SpriteKit for iOS using scenes, sprites, physics, and SwiftUI integration.

storekit
Build in-app purchases and subscriptions with StoreKit 2 paywalls, transaction handling, and entitlement verification.

swift-api-design-guidelines
Apply Swift API Design Guidelines to name, label, and document Swift APIs.

swift-architecture
Select, review, and migrate Apple-platform app architectures from MV to MVVM, MVI, TCA, Clean Architecture, Coordinator, and VIPER.

swift-charts
Build data visualizations with Swift Charts: bar, line, area, point, pie, donut, 3D, and vectorized plots for iOS 16+.

swift-codable
Encode and decode Swift types with Codable, JSONEncoder, JSONDecoder, and custom strategies for API responses and data persistence.