From fca3fb394c91f1c050dae9e2f311c1bbd254a0f7 Mon Sep 17 00:00:00 2001 From: rudrankriyam Date: Fri, 13 Nov 2026 17:11:25 +0530 Subject: [PATCH 01/10] Transcribe a selected audio track in local media --- README.md | 24 +++++ Sources/AuralKit/SpeechSession+File.swift | 95 +++++++++------- .../AuralKit/SpeechSession+MediaFile.swift | 101 ++++++++++++++++++ .../FileTranscriptionTests.swift | 22 ++++ 4 files changed, 202 insertions(+), 40 deletions(-) create mode 100644 Sources/AuralKit/SpeechSession+MediaFile.swift diff --git a/README.md b/README.md index 4359c19..24f6e90 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,7 @@ AuralKit is a simple, lightweight Swift wrapper for speech-to-text transcription - Async streams for lifecycle status, audio inputs, and transcription results - Device capability helper to inspect available transcribers and locales - Xcode 27-ready file transcription path that can use Speech's native analyzer file input when built with Swift 6.4+ +- Transcription from a selected audio track in a local movie or other media file on iOS and macOS 27+ - Xcode 27-ready live capture and analyzer preheating configuration with Xcode 26 fallbacks - ScreenCaptureKit-backed transcription for selected content audio on iOS 27+ and macOS 14+ - SwiftUI-friendly API that mirrors Apple's sample project design @@ -35,6 +36,7 @@ AuralKit is a simple, lightweight Swift wrapper for speech-to-text transcription - [Usage](#usage) - [Simple Transcription](#simple-transcription) - [Partial Results](#partial-results) + - [Media File Audio](#media-file-audio) - [Screen Capture Audio](#screen-capture-audio) - [Session Observability](#session-observability) - [Monitoring Model Downloads](#monitoring-model-downloads) @@ -276,6 +278,28 @@ struct ContentView: View { The `TranscriptionManager` in the demo app adds language selection, history tracking, and export. +### Media File Audio + +With Swift 6.4 and iOS or macOS 27+, pass a local media file to `streamTranscription(fromMediaFile:audioTrackID:options:)`. The default is the first audio track. Use `AVURLAsset` to find a particular audio track, then pass its `trackID`. + +```swift +import AVFoundation +import AuralKit + +let asset = AVURLAsset(url: movieURL) +let tracks = try await asset.loadTracks(withMediaType: .audio) + +if let commentary = tracks.dropFirst().first { + let session = SpeechSession() + let results = session.streamTranscription(fromMediaFile: movieURL, audioTrackID: commentary.trackID) + for try await result in results where result.isFinal { + print(result.text) + } +} +``` + +The file must be in an allowed directory, as with audio file transcription. `FileTranscriptionOptions.maxDuration` applies to the selected audio track. The app needs `NSSpeechRecognitionUsageDescription` for the Speech permission prompt. + ### Screen Capture Audio On OS versions where ScreenCaptureKit can stream selected content audio, AuralKit can transcribe audio chosen with the system picker: diff --git a/Sources/AuralKit/SpeechSession+File.swift b/Sources/AuralKit/SpeechSession+File.swift index 788925d..b009894 100644 --- a/Sources/AuralKit/SpeechSession+File.swift +++ b/Sources/AuralKit/SpeechSession+File.swift @@ -66,35 +66,15 @@ public extension SpeechSession { options: FileTranscriptionOptions = .init(), progressHandler: (@Sendable (Double) -> Void)? = nil ) -> AsyncThrowingStream { - let (stream, newContinuation) = AsyncThrowingStream.makeStream() - - guard continuation == nil, recognizerTask == nil, streamingMode == .inactive else { - newContinuation.finish(throwing: SpeechSessionError.recognitionStreamSetupFailed) - return stream - } - - let generation = beginStreamGeneration() - newContinuation.onTermination = { [weak self] _ in - Task { @MainActor [weak self] in - await self?.handleStreamTermination(generation: generation) - } - } - - setStatus(.preparing) - continuation = .speech(newContinuation) - - pipelineTask = Task { @MainActor [weak self] in - guard let self else { return } - await self.startFilePipeline( - with: newContinuation, + startFileTranscription { session, continuation, generation in + await session.startFilePipeline( + with: continuation, audioFileURL: audioFile, options: options, progressHandler: progressHandler, generation: generation ) } - - return stream } /// Convenience wrapper that collects final results from file transcription. @@ -152,22 +132,12 @@ private extension SpeechSession { generation: generation ) try Task.checkCancellation() - let handler = progressHandler - fileIngestionTask = Task { [weak self] in - guard let self else { return } - - do { - let completed = try await self.feedAudioFile( - validation, progressHandler: handler, generation: generation - ) - - if completed, let handler { - self.reportFileProgress(1.0, handler: handler, generation: generation) - } - } catch is CancellationError { - // Swallow cancellation triggered by cleanup. - } catch { - await self.finishWithStartupError(error, generation: generation) + startFileIngestion(generation: generation) { session in + let completed = try await session.feedAudioFile( + validation, progressHandler: progressHandler, generation: generation + ) + if completed, let progressHandler { + session.reportFileProgress(1.0, handler: progressHandler, generation: generation) } } } catch is CancellationError { @@ -213,7 +183,9 @@ private extension SpeechSession { return (audioFile, totalFrames) } +} +extension SpeechSession { func sanitizeAudioFileURL( _ url: URL, allowedDirectories: [URL] @@ -272,7 +244,9 @@ private extension SpeechSession { Self.logger.info("File transcription pipeline active (mode: file playback)") } } +} +private extension SpeechSession { nonisolated func feedAudioFile( _ payload: (file: AVAudioFile, totalFrames: AVAudioFramePosition), progressHandler: (@Sendable (Double) -> Void)?, @@ -344,10 +318,51 @@ private extension SpeechSession { #endif return false } - } extension SpeechSession { + typealias FileResultContinuation = AsyncThrowingStream.Continuation + + func startFileTranscription( + _ setup: @escaping @MainActor (SpeechSession, FileResultContinuation, Int) async -> Void + ) -> AsyncThrowingStream { + let (stream, newContinuation) = AsyncThrowingStream.makeStream() + guard continuation == nil, recognizerTask == nil, streamingMode == .inactive else { + newContinuation.finish(throwing: SpeechSessionError.recognitionStreamSetupFailed) + return stream + } + + let generation = beginStreamGeneration() + newContinuation.onTermination = { [weak self] _ in + Task { @MainActor [weak self] in + await self?.handleStreamTermination(generation: generation) + } + } + setStatus(.preparing) + continuation = .speech(newContinuation) + pipelineTask = Task { @MainActor [weak self] in + guard let self else { return } + await setup(self, newContinuation, generation) + } + return stream + } + + func startFileIngestion( + generation: Int, + _ ingest: @escaping @MainActor (SpeechSession) async throws -> Void + ) { + fileIngestionTask = Task { [weak self] in + guard let self else { return } + do { + try await ingest(self) + } catch is CancellationError { + // Cleanup cancelled the ingestion task. + } catch { + await finishWithStartupError(error, generation: generation) + } + } + } + func reportFileProgress( _ progress: Double, handler: @Sendable (Double) -> Void, diff --git a/Sources/AuralKit/SpeechSession+MediaFile.swift b/Sources/AuralKit/SpeechSession+MediaFile.swift new file mode 100644 index 0000000..f71353c --- /dev/null +++ b/Sources/AuralKit/SpeechSession+MediaFile.swift @@ -0,0 +1,101 @@ +#if swift(>=6.4) +import AVFoundation +import CoreMedia +import Foundation +import Speech + +@available(iOS 27.0, macOS 27.0, *) +public extension SpeechSession { + /// Stream transcription results from one audio track of a local media file, such as a movie. + /// + /// - Parameters: + /// - mediaFile: A local file URL in one of `options.allowedDirectories`. + /// - audioTrackID: An ID from the file's audio tracks. Pass `nil` to use its first audio track. + /// - options: Contextual strings, allowed directories, and the maximum selected track duration. + /// - Returns: An async throwing stream of transcription results on the media timeline. + func streamTranscription( + fromMediaFile mediaFile: URL, + audioTrackID: CMPersistentTrackID? = nil, + options: FileTranscriptionOptions = .init() + ) -> AsyncThrowingStream { + startFileTranscription { session, continuation, generation in + await session.startMediaFilePipeline( + mediaFile, audioTrackID: audioTrackID, options: options, + continuation: continuation, generation: generation + ) + } + } +} + +@available(iOS 27.0, macOS 27.0, *) +private extension SpeechSession { + func startMediaFilePipeline( + _ mediaFile: URL, + audioTrackID: CMPersistentTrackID?, + options: FileTranscriptionOptions, + continuation: FileResultContinuation, + generation: Int + ) async { + do { + try Task.checkCancellation() + let url = try sanitizeAudioFileURL(mediaFile, allowedDirectories: options.allowedDirectories) + let asset = AVURLAsset(url: url) + let track = try await loadAudioTrack(from: asset, id: audioTrackID, maxDuration: options.maxDuration) + try Task.checkCancellation() + try await ensureSpeechRecognitionAuthorization(context: "for media file transcription") + try Task.checkCancellation() + try await setUpFilePipeline( + with: continuation, + contextualStrings: options.contextualStrings, + startAnalyzerImmediately: false, + generation: generation + ) + try Task.checkCancellation() + guard let analyzer, let activeModules else { + throw SpeechSessionError.recognitionStreamSetupFailed + } + guard let format = await SpeechAnalyzer.bestAvailableAudioFormat(compatibleWith: activeModules) else { + throw SpeechSessionError.invalidAudioDataType + } + try Task.checkCancellation() + let provider = AssetInputSequenceProvider(asset: asset, track: track, analyzerFormat: format) + let inputs = provider.analyzerInputs + startFileIngestion(generation: generation) { session in + try await session.prepareAnalyzerForStartIfNeeded(in: format) + try Task.checkCancellation() + session.startSpeechDetectorMonitoringIfNeeded() + + let endTime = try await analyzer.analyzeSequence(inputs) + try Task.checkCancellation() + if let endTime { + try await analyzer.finalizeAndFinish(through: endTime) + } else { + try await analyzer.finalizeAndFinishThroughEndOfInput() + } + } + } catch { + await finishFailedPipelineSetup(error, generation: generation) + } + } + + func loadAudioTrack( + from asset: AVAsset, + id: CMPersistentTrackID?, + maxDuration: TimeInterval? + ) async throws -> AVAssetTrack { + let tracks = try await asset.loadTracks(withMediaType: .audio) + guard let track = tracks.first(where: { id == nil || $0.trackID == id }) else { + let reason = id.map { "Audio track ID \($0) was not found" } ?? "the media file has no audio tracks" + throw SpeechSessionError.audioFileUnsupportedFormat(reason) + } + let duration = try await track.load(.timeRange).duration.seconds + guard duration.isFinite, duration > 0 else { + throw SpeechSessionError.audioFileUnsupportedFormat("the audio track has no finite, positive duration") + } + if let maxDuration, duration > maxDuration { + throw SpeechSessionError.audioFileTooLong(maximum: maxDuration, actual: duration) + } + return track + } +} +#endif diff --git a/Tests/AuralKitTests/FileTranscriptionTests.swift b/Tests/AuralKitTests/FileTranscriptionTests.swift index 68fd118..2bf24ea 100644 --- a/Tests/AuralKitTests/FileTranscriptionTests.swift +++ b/Tests/AuralKitTests/FileTranscriptionTests.swift @@ -30,6 +30,28 @@ struct FileTranscriptionTests { } } +#if swift(>=6.4) + @available(iOS 27.0, macOS 27.0, *) + @Test("Media transcription rejects an unknown audio track without falling back") + @MainActor + func mediaTranscriptionRejectsUnknownTrack() async throws { + let url = try createSilenceAudioFile(duration: 2.0) + defer { try? FileManager.default.removeItem(at: url) } + let asset = AVURLAsset(url: url) + let tracks = try await asset.loadTracks(withMediaType: .audio) + let track = try #require(tracks.first) + let session = SpeechSession() + + let stream = session.streamTranscription(fromMediaFile: url, audioTrackID: track.trackID + 1) + do { + for try await _ in stream { } + Issue.record("Expected the unknown track to be rejected") + } catch SpeechSessionError.audioFileUnsupportedFormat(let reason) { + #expect(reason.contains("\(track.trackID + 1)")) + } + } +#endif + private func createSilenceAudioFile(duration: TimeInterval, sampleRate: Double = 44_100) throws -> URL { let tempURL = FileManager.default.temporaryDirectory .appendingPathComponent(UUID().uuidString) From 8c538678145a2a0e043a956a1beacd83fee1bfa2 Mon Sep 17 00:00:00 2001 From: rudrankriyam Date: Fri, 13 Nov 2026 17:16:13 +0530 Subject: [PATCH 02/10] Validate media references and duration before transcription --- README.md | 2 +- .../AuralKit/SpeechSession+MediaFile.swift | 26 ++++++++++++++++--- 2 files changed, 24 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 24f6e90..ac6582d 100644 --- a/README.md +++ b/README.md @@ -298,7 +298,7 @@ if let commentary = tracks.dropFirst().first { } ``` -The file must be in an allowed directory, as with audio file transcription. `FileTranscriptionOptions.maxDuration` applies to the selected audio track. The app needs `NSSpeechRecognitionUsageDescription` for the Speech permission prompt. +Use the default `.automatic` input provider. The file must be in an allowed directory and contain its audio. `FileTranscriptionOptions.maxDuration` applies to the selected track’s duration on the media timeline. The app needs `NSSpeechRecognitionUsageDescription` for the Speech permission prompt. ### Screen Capture Audio diff --git a/Sources/AuralKit/SpeechSession+MediaFile.swift b/Sources/AuralKit/SpeechSession+MediaFile.swift index f71353c..256fbeb 100644 --- a/Sources/AuralKit/SpeechSession+MediaFile.swift +++ b/Sources/AuralKit/SpeechSession+MediaFile.swift @@ -13,6 +13,8 @@ public extension SpeechSession { /// - audioTrackID: An ID from the file's audio tracks. Pass `nil` to use its first audio track. /// - options: Contextual strings, allowed directories, and the maximum selected track duration. /// - Returns: An async throwing stream of transcription results on the media timeline. + /// + /// The audio must be stored inside the media file and the session must use `.automatic` input. func streamTranscription( fromMediaFile mediaFile: URL, audioTrackID: CMPersistentTrackID? = nil, @@ -38,8 +40,17 @@ private extension SpeechSession { ) async { do { try Task.checkCancellation() + guard inputProviderPreference == .automatic else { + throw SpeechSessionError.audioFileUnsupportedFormat(NSLocalizedString( + "media transcription requires the automatic input provider", + comment: "Media files cannot use the legacy audio input pipeline" + )) + } let url = try sanitizeAudioFileURL(mediaFile, allowedDirectories: options.allowedDirectories) - let asset = AVURLAsset(url: url) + let asset = AVURLAsset(url: url, options: [ + AVURLAssetReferenceRestrictionsKey: AVAssetReferenceRestrictions.forbidAll.rawValue, + AVURLAssetPreferPreciseDurationAndTimingKey: options.maxDuration != nil + ]) let track = try await loadAudioTrack(from: asset, id: audioTrackID, maxDuration: options.maxDuration) try Task.checkCancellation() try await ensureSpeechRecognitionAuthorization(context: "for media file transcription") @@ -85,12 +96,21 @@ private extension SpeechSession { ) async throws -> AVAssetTrack { let tracks = try await asset.loadTracks(withMediaType: .audio) guard let track = tracks.first(where: { id == nil || $0.trackID == id }) else { - let reason = id.map { "Audio track ID \($0) was not found" } ?? "the media file has no audio tracks" + let reason = if let id { + String.localizedStringWithFormat(NSLocalizedString( + "audio track ID %d was not found", comment: "The requested audio track is missing" + ), id) + } else { + NSLocalizedString("the media file has no audio tracks", comment: "The media asset has no audio track") + } throw SpeechSessionError.audioFileUnsupportedFormat(reason) } let duration = try await track.load(.timeRange).duration.seconds guard duration.isFinite, duration > 0 else { - throw SpeechSessionError.audioFileUnsupportedFormat("the audio track has no finite, positive duration") + throw SpeechSessionError.audioFileUnsupportedFormat(NSLocalizedString( + "the audio track has no finite, positive duration", + comment: "The media audio track has no usable duration" + )) } if let maxDuration, duration > maxDuration { throw SpeechSessionError.audioFileTooLong(maximum: maxDuration, actual: duration) From 0bdda6829a452f26c01f6e2a69268982fac0abfb Mon Sep 17 00:00:00 2001 From: rudrankriyam Date: Fri, 13 Nov 2026 17:18:20 +0530 Subject: [PATCH 03/10] Omit precise timing option without a media duration limit --- Sources/AuralKit/SpeechSession+MediaFile.swift | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/Sources/AuralKit/SpeechSession+MediaFile.swift b/Sources/AuralKit/SpeechSession+MediaFile.swift index 256fbeb..479ff38 100644 --- a/Sources/AuralKit/SpeechSession+MediaFile.swift +++ b/Sources/AuralKit/SpeechSession+MediaFile.swift @@ -47,10 +47,7 @@ private extension SpeechSession { )) } let url = try sanitizeAudioFileURL(mediaFile, allowedDirectories: options.allowedDirectories) - let asset = AVURLAsset(url: url, options: [ - AVURLAssetReferenceRestrictionsKey: AVAssetReferenceRestrictions.forbidAll.rawValue, - AVURLAssetPreferPreciseDurationAndTimingKey: options.maxDuration != nil - ]) + let asset = Self.makeMediaAsset(url: url, needsPreciseDuration: options.maxDuration != nil) let track = try await loadAudioTrack(from: asset, id: audioTrackID, maxDuration: options.maxDuration) try Task.checkCancellation() try await ensureSpeechRecognitionAuthorization(context: "for media file transcription") @@ -89,6 +86,16 @@ private extension SpeechSession { } } + static func makeMediaAsset(url: URL, needsPreciseDuration: Bool) -> AVURLAsset { + var options: [String: Any] = [ + AVURLAssetReferenceRestrictionsKey: AVAssetReferenceRestrictions.forbidAll.rawValue + ] + if needsPreciseDuration { + options[AVURLAssetPreferPreciseDurationAndTimingKey] = true + } + return AVURLAsset(url: url, options: options) + } + func loadAudioTrack( from asset: AVAsset, id: CMPersistentTrackID?, From 1582336609a1e8065b9df90470bc46cc79811173 Mon Sep 17 00:00:00 2001 From: rudrankriyam Date: Fri, 13 Nov 2026 17:23:58 +0530 Subject: [PATCH 04/10] Close media analysis when no audio samples arrive --- Sources/AuralKit/SpeechSession+MediaFile.swift | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/Sources/AuralKit/SpeechSession+MediaFile.swift b/Sources/AuralKit/SpeechSession+MediaFile.swift index 479ff38..66e5c45 100644 --- a/Sources/AuralKit/SpeechSession+MediaFile.swift +++ b/Sources/AuralKit/SpeechSession+MediaFile.swift @@ -78,7 +78,13 @@ private extension SpeechSession { if let endTime { try await analyzer.finalizeAndFinish(through: endTime) } else { - try await analyzer.finalizeAndFinishThroughEndOfInput() + // With no input samples, Speech may leave the module's results stream open. + await analyzer.cancelAndFinishNow() + try Task.checkCancellation() + guard generation == session.sessionGeneration else { return } + session.prepareForStop() + await session.cleanup(cancelRecognizer: true, generation: generation) + await session.finishStream(error: nil, generation: generation) } } } catch { From a5895d66648e9d73b22308377e5ac1d6e8206d10 Mon Sep 17 00:00:00 2001 From: rudrankriyam Date: Fri, 13 Nov 2026 17:27:06 +0530 Subject: [PATCH 05/10] Cancel file analyzer teardown before input starts --- .../AuralKit/SpeechSession+MediaFile.swift | 3 --- Sources/AuralKit/SpeechSession+Pipeline.swift | 2 +- .../AuralKit/SpeechSession+Transcriber.swift | 10 +++++++++- .../FileTranscriptionTests.swift | 19 +++++++++++++++++++ 4 files changed, 29 insertions(+), 5 deletions(-) diff --git a/Sources/AuralKit/SpeechSession+MediaFile.swift b/Sources/AuralKit/SpeechSession+MediaFile.swift index 66e5c45..1f33208 100644 --- a/Sources/AuralKit/SpeechSession+MediaFile.swift +++ b/Sources/AuralKit/SpeechSession+MediaFile.swift @@ -79,9 +79,6 @@ private extension SpeechSession { try await analyzer.finalizeAndFinish(through: endTime) } else { // With no input samples, Speech may leave the module's results stream open. - await analyzer.cancelAndFinishNow() - try Task.checkCancellation() - guard generation == session.sessionGeneration else { return } session.prepareForStop() await session.cleanup(cancelRecognizer: true, generation: generation) await session.finishStream(error: nil, generation: generation) diff --git a/Sources/AuralKit/SpeechSession+Pipeline.swift b/Sources/AuralKit/SpeechSession+Pipeline.swift index 97c0395..5aeabf8 100644 --- a/Sources/AuralKit/SpeechSession+Pipeline.swift +++ b/Sources/AuralKit/SpeechSession+Pipeline.swift @@ -306,7 +306,7 @@ extension SpeechSession { #endif let detached = detachTranscriberState() await stopScreenCaptureStreamingIfNeeded() - await finalizeDetachedTranscriberState(detached) + await finalizeDetachedTranscriberState(detached, cancelAnalysis: cancelRecognizer) guard generation == sessionGeneration else { return } await modelManager.releaseLocales() diff --git a/Sources/AuralKit/SpeechSession+Transcriber.swift b/Sources/AuralKit/SpeechSession+Transcriber.swift index 460ddcf..057c112 100644 --- a/Sources/AuralKit/SpeechSession+Transcriber.swift +++ b/Sources/AuralKit/SpeechSession+Transcriber.swift @@ -297,9 +297,17 @@ extension SpeechSession { /// /// Operates only on the captured references, never on live session state, so it is safe to /// run even after a newer session has started. - func finalizeDetachedTranscriberState(_ detached: DetachedTranscriberState) async { + func finalizeDetachedTranscriberState( + _ detached: DetachedTranscriberState, + cancelAnalysis: Bool = false + ) async { defer { withExtendedLifetime(detached.vocabularyArtifacts) {} } detached.inputBuilder?.finish() + if cancelAnalysis { + // Finalizing waits for EOF, which may never arrive if setup was cancelled. + await detached.analyzer?.cancelAndFinishNow() + return + } do { try await detached.analyzer?.finalizeAndFinishThroughEndOfInput() } catch { diff --git a/Tests/AuralKitTests/FileTranscriptionTests.swift b/Tests/AuralKitTests/FileTranscriptionTests.swift index 2bf24ea..6ff123f 100644 --- a/Tests/AuralKitTests/FileTranscriptionTests.swift +++ b/Tests/AuralKitTests/FileTranscriptionTests.swift @@ -1,5 +1,6 @@ import Testing import AVFoundation +import Speech @testable import AuralKit @Suite("File transcription") @@ -31,6 +32,24 @@ struct FileTranscriptionTests { } #if swift(>=6.4) + @Test("Stopping a file analyzer before it receives input closes the session") + @MainActor + func stopBeforeAnalyzerInputClosesSession() async throws { + let session = SpeechSession() + let (results, continuation) = AsyncThrowingStream.makeStream() + session.analyzer = SpeechAnalyzer(modules: []) + session.continuation = .speech(continuation) + session.streamingMode = .filePlayback + session.setStatus(.preparing) + + try await awaitResult(timeout: 3) { await session.stopTranscribing() } + + var iterator = results.makeAsyncIterator() + let nextResult = try await iterator.next() + #expect(nextResult == nil) + #expect(session.status == .idle) + } + @available(iOS 27.0, macOS 27.0, *) @Test("Media transcription rejects an unknown audio track without falling back") @MainActor From 938cf9d812ba26d424d7363dff06a6ac5792ad01 Mon Sep 17 00:00:00 2001 From: rudrankriyam Date: Fri, 13 Nov 2026 17:32:29 +0530 Subject: [PATCH 06/10] Unblock the analyzer if the stop regression test times out --- Tests/AuralKitTests/FileTranscriptionTests.swift | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/Tests/AuralKitTests/FileTranscriptionTests.swift b/Tests/AuralKitTests/FileTranscriptionTests.swift index 6ff123f..d8d4741 100644 --- a/Tests/AuralKitTests/FileTranscriptionTests.swift +++ b/Tests/AuralKitTests/FileTranscriptionTests.swift @@ -37,12 +37,24 @@ struct FileTranscriptionTests { func stopBeforeAnalyzerInputClosesSession() async throws { let session = SpeechSession() let (results, continuation) = AsyncThrowingStream.makeStream() - session.analyzer = SpeechAnalyzer(modules: []) + let analyzer = SpeechAnalyzer(modules: []) + session.analyzer = analyzer session.continuation = .speech(continuation) session.streamingMode = .filePlayback session.setStatus(.preparing) - try await awaitResult(timeout: 3) { await session.stopTranscribing() } + let watchdog = Task { + do { + try await Task.sleep(for: .seconds(3)) + Issue.record("Stopping an analyzer with no input did not return") + await analyzer.cancelAndFinishNow() + } catch is CancellationError { + // Stop completed before the deadline. + } + } + await session.stopTranscribing() + watchdog.cancel() + try await watchdog.value var iterator = results.makeAsyncIterator() let nextResult = try await iterator.next() From 878e5fd38b34d4312c24f1fdf1c912616d7b1a3c Mon Sep 17 00:00:00 2001 From: rudrankriyam Date: Fri, 13 Nov 2026 17:38:41 +0530 Subject: [PATCH 07/10] Preserve file ingestion errors when cancelling the recognizer --- Sources/AuralKit/SpeechSession+Pipeline.swift | 3 ++ .../FileTranscriptionTests.swift | 30 +++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/Sources/AuralKit/SpeechSession+Pipeline.swift b/Sources/AuralKit/SpeechSession+Pipeline.swift index 5aeabf8..102501c 100644 --- a/Sources/AuralKit/SpeechSession+Pipeline.swift +++ b/Sources/AuralKit/SpeechSession+Pipeline.swift @@ -441,8 +441,10 @@ extension SpeechSession { do { for try await result in results { + try Task.checkCancellation() streamContinuation.yield(result) } + try Task.checkCancellation() if Self.shouldLog(.notice) { Self.logger.notice("\(label, privacy: .public) completed without error") } @@ -452,6 +454,7 @@ extension SpeechSession { Self.logger.debug("\(label, privacy: .public) cancelled") } } catch { + guard !Task.isCancelled else { return } if Self.shouldLog(.error) { Self.logger.error( "\(label, privacy: .public) failed: \(error.localizedDescription, privacy: .public)" diff --git a/Tests/AuralKitTests/FileTranscriptionTests.swift b/Tests/AuralKitTests/FileTranscriptionTests.swift index d8d4741..73ccac9 100644 --- a/Tests/AuralKitTests/FileTranscriptionTests.swift +++ b/Tests/AuralKitTests/FileTranscriptionTests.swift @@ -62,6 +62,36 @@ struct FileTranscriptionTests { #expect(session.status == .idle) } + @Test("A cancelled recognizer cannot hide a file read error") + @MainActor + func fileReadErrorSurvivesRecognizerCancellation() async throws { + let session = SpeechSession() + let output = AsyncThrowingStream.makeStream() + let results = AsyncStream.makeStream() + let generation = session.beginStreamGeneration() + session.continuation = .speech(output.continuation) + session.streamingMode = .filePlayback + session.setStatus(.transcribing) + let recognizer = session.createRecognizerTask( + label: "File recognizer", results: results.stream, + streamContinuation: output.continuation, generation: generation + ) + session.recognizerTask = recognizer + session.startFileIngestion(generation: generation) { _ in + throw SpeechSessionError.audioFileReadFailed(nil) + } + let ingestion = try #require(session.fileIngestionTask) + + await recognizer.value + await ingestion.value + var iterator = output.stream.makeAsyncIterator() + do { + _ = try await iterator.next() + Issue.record("Expected the file read error to reach the transcription stream") + } catch SpeechSessionError.audioFileReadFailed { } + #expect(session.status == .idle) + } + @available(iOS 27.0, macOS 27.0, *) @Test("Media transcription rejects an unknown audio track without falling back") @MainActor From c69aba53d2d73a247f83f0172f417e42c85d630e Mon Sep 17 00:00:00 2001 From: rudrankriyam Date: Fri, 13 Nov 2026 17:40:25 +0530 Subject: [PATCH 08/10] Exercise the native Speech recognizer in the file error regression --- Tests/AuralKitTests/FileTranscriptionTests.swift | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Tests/AuralKitTests/FileTranscriptionTests.swift b/Tests/AuralKitTests/FileTranscriptionTests.swift index 73ccac9..d1f0cc2 100644 --- a/Tests/AuralKitTests/FileTranscriptionTests.swift +++ b/Tests/AuralKitTests/FileTranscriptionTests.swift @@ -67,14 +67,14 @@ struct FileTranscriptionTests { func fileReadErrorSurvivesRecognizerCancellation() async throws { let session = SpeechSession() let output = AsyncThrowingStream.makeStream() - let results = AsyncStream.makeStream() + let transcriber = SpeechTranscriber(locale: Locale(identifier: "en-US"), preset: .transcription) + session.analyzer = SpeechAnalyzer(modules: [transcriber]) let generation = session.beginStreamGeneration() session.continuation = .speech(output.continuation) session.streamingMode = .filePlayback session.setStatus(.transcribing) - let recognizer = session.createRecognizerTask( - label: "File recognizer", results: results.stream, - streamContinuation: output.continuation, generation: generation + let recognizer = session.createSpeechRecognizerTask( + transcriber: transcriber, streamContinuation: output.continuation, generation: generation ) session.recognizerTask = recognizer session.startFileIngestion(generation: generation) { _ in From 149545c5af2ff42015843c21cbf9106d7ce04a90 Mon Sep 17 00:00:00 2001 From: rudrankriyam Date: Fri, 13 Nov 2026 17:46:02 +0530 Subject: [PATCH 09/10] Limit immediate teardown to media playback --- Sources/AuralKit/SpeechSession+File.swift | 5 +++- .../AuralKit/SpeechSession+MediaFile.swift | 24 +++++++++++++++---- Sources/AuralKit/SpeechSession+Pipeline.swift | 3 ++- Sources/AuralKit/SpeechSession+Types.swift | 1 + .../FileTranscriptionTests.swift | 6 ++--- 5 files changed, 29 insertions(+), 10 deletions(-) diff --git a/Sources/AuralKit/SpeechSession+File.swift b/Sources/AuralKit/SpeechSession+File.swift index b009894..8e63ce9 100644 --- a/Sources/AuralKit/SpeechSession+File.swift +++ b/Sources/AuralKit/SpeechSession+File.swift @@ -219,6 +219,7 @@ extension SpeechSession { with streamContinuation: AsyncThrowingStream.Continuation, contextualStrings: [AnalysisContext.ContextualStringsTag: [String]]?, startAnalyzerImmediately: Bool, + mode: StreamingMode = .filePlayback, generation: Int ) async throws { if Self.shouldLog(.notice) { @@ -238,7 +239,7 @@ extension SpeechSession { generation: generation ) - streamingMode = .filePlayback + streamingMode = mode setStatus(.transcribing) if Self.shouldLog(.info) { Self.logger.info("File transcription pipeline active (mode: file playback)") @@ -324,6 +325,7 @@ extension SpeechSession { typealias FileResultContinuation = AsyncThrowingStream.Continuation func startFileTranscription( + mode: StreamingMode = .filePlayback, _ setup: @escaping @MainActor (SpeechSession, FileResultContinuation, Int) async -> Void ) -> AsyncThrowingStream { let (stream, newContinuation) = AsyncThrowingStream.makeStream() @@ -338,6 +340,7 @@ extension SpeechSession { await self?.handleStreamTermination(generation: generation) } } + if mode == .mediaPlayback { streamingMode = mode } setStatus(.preparing) continuation = .speech(newContinuation) pipelineTask = Task { @MainActor [weak self] in diff --git a/Sources/AuralKit/SpeechSession+MediaFile.swift b/Sources/AuralKit/SpeechSession+MediaFile.swift index 1f33208..56903fb 100644 --- a/Sources/AuralKit/SpeechSession+MediaFile.swift +++ b/Sources/AuralKit/SpeechSession+MediaFile.swift @@ -20,7 +20,7 @@ public extension SpeechSession { audioTrackID: CMPersistentTrackID? = nil, options: FileTranscriptionOptions = .init() ) -> AsyncThrowingStream { - startFileTranscription { session, continuation, generation in + startFileTranscription(mode: .mediaPlayback) { session, continuation, generation in await session.startMediaFilePipeline( mediaFile, audioTrackID: audioTrackID, options: options, continuation: continuation, generation: generation @@ -41,10 +41,7 @@ private extension SpeechSession { do { try Task.checkCancellation() guard inputProviderPreference == .automatic else { - throw SpeechSessionError.audioFileUnsupportedFormat(NSLocalizedString( - "media transcription requires the automatic input provider", - comment: "Media files cannot use the legacy audio input pipeline" - )) + throw MediaTranscriptionConfigurationError() } let url = try sanitizeAudioFileURL(mediaFile, allowedDirectories: options.allowedDirectories) let asset = Self.makeMediaAsset(url: url, needsPreciseDuration: options.maxDuration != nil) @@ -56,6 +53,7 @@ private extension SpeechSession { with: continuation, contextualStrings: options.contextualStrings, startAnalyzerImmediately: false, + mode: .mediaPlayback, generation: generation ) try Task.checkCancellation() @@ -128,4 +126,20 @@ private extension SpeechSession { return track } } + +private struct MediaTranscriptionConfigurationError: LocalizedError { + var errorDescription: String? { + NSLocalizedString( + "Media transcription requires the automatic input provider.", + comment: "Media files cannot use the legacy audio input pipeline" + ) + } + + var recoverySuggestion: String? { + NSLocalizedString( + "Create a SpeechSession with inputProviderPreference set to .automatic.", + comment: "How to enable media transcription" + ) + } +} #endif diff --git a/Sources/AuralKit/SpeechSession+Pipeline.swift b/Sources/AuralKit/SpeechSession+Pipeline.swift index 102501c..76bf5f4 100644 --- a/Sources/AuralKit/SpeechSession+Pipeline.swift +++ b/Sources/AuralKit/SpeechSession+Pipeline.swift @@ -296,6 +296,7 @@ extension SpeechSession { task?.cancel() } + let cancelMediaAnalysis = cancelRecognizer && streamingMode == .mediaPlayback streamingMode = .inactive activeResultKind = nil stopAudioStreaming() @@ -306,7 +307,7 @@ extension SpeechSession { #endif let detached = detachTranscriberState() await stopScreenCaptureStreamingIfNeeded() - await finalizeDetachedTranscriberState(detached, cancelAnalysis: cancelRecognizer) + await finalizeDetachedTranscriberState(detached, cancelAnalysis: cancelMediaAnalysis) guard generation == sessionGeneration else { return } await modelManager.releaseLocales() diff --git a/Sources/AuralKit/SpeechSession+Types.swift b/Sources/AuralKit/SpeechSession+Types.swift index a874707..6576642 100644 --- a/Sources/AuralKit/SpeechSession+Types.swift +++ b/Sources/AuralKit/SpeechSession+Types.swift @@ -18,6 +18,7 @@ extension SpeechSession { case inactive case liveMicrophone case filePlayback + case mediaPlayback case screenCapture } diff --git a/Tests/AuralKitTests/FileTranscriptionTests.swift b/Tests/AuralKitTests/FileTranscriptionTests.swift index d1f0cc2..b50701a 100644 --- a/Tests/AuralKitTests/FileTranscriptionTests.swift +++ b/Tests/AuralKitTests/FileTranscriptionTests.swift @@ -32,7 +32,7 @@ struct FileTranscriptionTests { } #if swift(>=6.4) - @Test("Stopping a file analyzer before it receives input closes the session") + @Test("Stopping a media analyzer before it receives input closes the session") @MainActor func stopBeforeAnalyzerInputClosesSession() async throws { let session = SpeechSession() @@ -40,7 +40,7 @@ struct FileTranscriptionTests { let analyzer = SpeechAnalyzer(modules: []) session.analyzer = analyzer session.continuation = .speech(continuation) - session.streamingMode = .filePlayback + session.streamingMode = .mediaPlayback session.setStatus(.preparing) let watchdog = Task { @@ -71,7 +71,7 @@ struct FileTranscriptionTests { session.analyzer = SpeechAnalyzer(modules: [transcriber]) let generation = session.beginStreamGeneration() session.continuation = .speech(output.continuation) - session.streamingMode = .filePlayback + session.streamingMode = .mediaPlayback session.setStatus(.transcribing) let recognizer = session.createSpeechRecognizerTask( transcriber: transcriber, streamContinuation: output.continuation, generation: generation From ec08f031786ee4aa2d0e45c828a1837ccb9b7de5 Mon Sep 17 00:00:00 2001 From: rudrankriyam Date: Fri, 13 Nov 2026 17:51:07 +0530 Subject: [PATCH 10/10] Forward recognizer results already queued at stop --- Sources/AuralKit/SpeechSession+Pipeline.swift | 1 - 1 file changed, 1 deletion(-) diff --git a/Sources/AuralKit/SpeechSession+Pipeline.swift b/Sources/AuralKit/SpeechSession+Pipeline.swift index 76bf5f4..8487114 100644 --- a/Sources/AuralKit/SpeechSession+Pipeline.swift +++ b/Sources/AuralKit/SpeechSession+Pipeline.swift @@ -442,7 +442,6 @@ extension SpeechSession { do { for try await result in results { - try Task.checkCancellation() streamContinuation.yield(result) } try Task.checkCancellation()