2026-07-03 22:13:16 +02:00
import AVFoundation
import Speech
2026-07-03 23:57:49 +02:00
/// The transcribing service that transcribes recorded audio into text on device.
2026-07-03 22:13:16 +02:00
///
/// The service writes the recorded audio into a temporary `.m4a` file and runs it through a `SpeechAnalyzer` with a `SpeechTranscriber`
2026-07-04 12:03:19 +02:00
/// module, joining the finalized results into the returned transcription. The transcription happens in the locale given at each call — or rather in the
2026-07-04 10:15:18 +02:00
/// closest equivalent the transcriber supports. The speech model assets for that locale are downloaded and installed on first use; every
/// transcription after that happens entirely offline.
2026-07-04 12:03:19 +02:00
public struct AudioTranscribing : Transcribing {
2026-07-04 10:15:18 +02:00
2026-07-03 22:13:16 +02:00
// MARK: Initializers
2026-07-04 12:03:19 +02:00
/// Creates an audio transcribing service.
public init () {}
2026-07-03 22:13:16 +02:00
// MARK: Methods
/// Transcribes the given recorded audio into text, deleting the temporary audio file when the transcription finishes.
///
2026-07-04 12:03:19 +02:00
/// - Parameters:
/// - audio: The recorded audio to transcribe.
/// - locale: The locale of the spoken language to transcribe.
2026-07-03 22:13:16 +02:00
/// - Returns: The transcription of the recorded audio.
2026-07-04 12:03:19 +02:00
/// - Throws: ``AudioTranscribingError/localeNotSupported`` when the transcriber supports no equivalent of the given locale,
2026-07-04 10:15:18 +02:00
/// or any error thrown while installing the speech model assets, reading the audio file, or analyzing its contents.
2026-07-04 12:03:19 +02:00
public func callAsFunction (
_ audio : Data ,
locale : Locale
) async throws -> Transcription {
2026-07-03 22:13:16 +02:00
try audio . write ( to : Constant . File . url )
defer {
try ? FileManager . default . removeItem ( at : Constant . File . url )
}
2026-07-04 10:15:18 +02:00
guard let locale = await SpeechTranscriber . supportedLocale (
equivalentTo : locale
) else {
2026-07-03 22:13:16 +02:00
throw AudioTranscribingError . localeNotSupported
}
let transcriber = SpeechTranscriber (
locale : locale ,
preset : . transcription
)
if let request = try await AssetInventory . assetInstallationRequest ( supporting : [ transcriber ]) {
try await request . downloadAndInstall ()
}
let analyzer = SpeechAnalyzer ( modules : [ transcriber ])
async let text = transcriber . results . reduce ( into : "" ) { text , result in
text += String ( result . text . characters )
}
let file = try AVAudioFile ( forReading : Constant . File . url )
if let lastSampleTime = try await analyzer . analyzeSequence ( from : file ) {
try await analyzer . finalizeAndFinish ( through : lastSampleTime )
} else {
await analyzer . cancelAndFinishNow ()
}
2026-07-04 12:03:19 +02:00
return try await . init ( text : text )
2026-07-03 22:13:16 +02:00
}
}
// MARK: - Errors
2026-07-04 12:03:19 +02:00
/// The errors thrown by ``AudioTranscribing``.
2026-07-03 23:57:49 +02:00
public enum AudioTranscribingError : Error {
2026-07-04 12:03:19 +02:00
/// The transcriber supports no equivalent of the locale the transcription was requested with.
2026-07-03 22:13:16 +02:00
case localeNotSupported
}
// MARK: - Constants
2026-07-03 23:57:49 +02:00
/// The constant values used across the audio transcribing service.
private enum Constant {
2026-07-03 22:13:16 +02:00
/// The file constants.
enum File {
/// The location of the temporary file the recorded audio is written into for the analysis.
static let url = FileManager . default . temporaryDirectory . appending ( path : "transcription.m4a" )
}
}