Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)
Expand Down Expand Up @@ -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)
}
}
```

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

On OS versions where ScreenCaptureKit can stream selected content audio, AuralKit can transcribe audio chosen with the system picker:
Expand Down
100 changes: 59 additions & 41 deletions Sources/AuralKit/SpeechSession+File.swift
Original file line number Diff line number Diff line change
Expand Up @@ -66,35 +66,15 @@ public extension SpeechSession {
options: FileTranscriptionOptions = .init(),
progressHandler: (@Sendable (Double) -> Void)? = nil
) -> AsyncThrowingStream<SpeechTranscriber.Result, Error> {
let (stream, newContinuation) = AsyncThrowingStream<SpeechTranscriber.Result, Error>.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.
Expand Down Expand Up @@ -152,22 +132,12 @@ private extension SpeechSession {
generation: generation
)
try Task.checkCancellation()
let handler = progressHandler
fileIngestionTask = Task<Void, Never> { [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 {
Expand Down Expand Up @@ -213,7 +183,9 @@ private extension SpeechSession {

return (audioFile, totalFrames)
}
}

extension SpeechSession {
func sanitizeAudioFileURL(
_ url: URL,
allowedDirectories: [URL]
Expand Down Expand Up @@ -247,6 +219,7 @@ private extension SpeechSession {
with streamContinuation: AsyncThrowingStream<SpeechTranscriber.Result, Error>.Continuation,
contextualStrings: [AnalysisContext.ContextualStringsTag: [String]]?,
startAnalyzerImmediately: Bool,
mode: StreamingMode = .filePlayback,
generation: Int
) async throws {
if Self.shouldLog(.notice) {
Expand All @@ -266,13 +239,15 @@ private extension SpeechSession {
generation: generation
)

streamingMode = .filePlayback
streamingMode = mode
setStatus(.transcribing)
if Self.shouldLog(.info) {
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)?,
Expand Down Expand Up @@ -344,10 +319,53 @@ private extension SpeechSession {
#endif
return false
}

}

extension SpeechSession {
typealias FileResultContinuation = AsyncThrowingStream<SpeechTranscriber.Result, Error>.Continuation

func startFileTranscription(
mode: StreamingMode = .filePlayback,
_ setup: @escaping @MainActor (SpeechSession, FileResultContinuation, Int) async -> Void
) -> AsyncThrowingStream<SpeechTranscriber.Result, Error> {
let (stream, newContinuation) = AsyncThrowingStream<SpeechTranscriber.Result, Error>.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)
}
}
if mode == .mediaPlayback { streamingMode = mode }
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,
Expand Down
145 changes: 145 additions & 0 deletions Sources/AuralKit/SpeechSession+MediaFile.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
#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.
///
/// The audio must be stored inside the media file and the session must use `.automatic` input.
func streamTranscription(
fromMediaFile mediaFile: URL,
audioTrackID: CMPersistentTrackID? = nil,
options: FileTranscriptionOptions = .init()
) -> AsyncThrowingStream<SpeechTranscriber.Result, Error> {
startFileTranscription(mode: .mediaPlayback) { 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()
guard inputProviderPreference == .automatic else {
throw MediaTranscriptionConfigurationError()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Private error skips SpeechSessionError

Medium Severity

A non-automatic inputProviderPreference now throws private MediaTranscriptionConfigurationError instead of SpeechSessionError. Callers that catch SpeechSessionError (as the public docs describe) miss this failure, and the type is not visible outside the module so it cannot be handled by name.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 149545c. Configure here.

}
let url = try sanitizeAudioFileURL(mediaFile, allowedDirectories: options.allowedDirectories)
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")
try Task.checkCancellation()
try await setUpFilePipeline(
with: continuation,
contextualStrings: options.contextualStrings,
startAnalyzerImmediately: false,
mode: .mediaPlayback,
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 {
// With no input samples, Speech may leave the module's results stream open.
session.prepareForStop()
await session.cleanup(cancelRecognizer: true, generation: generation)
await session.finishStream(error: nil, generation: generation)
}
}
} catch {
await finishFailedPipelineSetup(error, generation: generation)
}
}

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?,
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 = 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(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)
}
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
5 changes: 4 additions & 1 deletion Sources/AuralKit/SpeechSession+Pipeline.swift
Original file line number Diff line number Diff line change
Expand Up @@ -296,6 +296,7 @@ extension SpeechSession {
task?.cancel()
}

let cancelMediaAnalysis = cancelRecognizer && streamingMode == .mediaPlayback
streamingMode = .inactive
activeResultKind = nil
stopAudioStreaming()
Expand All @@ -306,7 +307,7 @@ extension SpeechSession {
#endif
let detached = detachTranscriberState()
await stopScreenCaptureStreamingIfNeeded()
await finalizeDetachedTranscriberState(detached)
await finalizeDetachedTranscriberState(detached, cancelAnalysis: cancelMediaAnalysis)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stop cancel limited to media

High Severity

cleanup now calls cancelAndFinishNow() only when streamingMode is .mediaPlayback. finalizeAndFinishThroughEndOfInput() waits for input that never arrives if setup is cancelled before the analyzer is started, so stopTranscribing() can hang for live or file sessions during preparing (including model download). The hang test was retargeted to media, so that path is no longer covered.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 149545c. Configure here.


guard generation == sessionGeneration else { return }
await modelManager.releaseLocales()
Expand Down Expand Up @@ -443,6 +444,7 @@ extension SpeechSession {
for try await result in results {
streamContinuation.yield(result)
}
try Task.checkCancellation()
if Self.shouldLog(.notice) {
Self.logger.notice("\(label, privacy: .public) completed without error")
}
Expand All @@ -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)"
Expand Down
Loading