Save Speech Transcripts Without Losing Their Timestamps
A recording app transcribes an interview. The words highlight during playback, the transcript saves successfully, and tomorrow every word is still there. Except tapping a passage no longer knows where to seek.
The transcript remembered the conversation. It forgot the appointment times.
SpeechTranscriber puts timing in an AttributedString. Saving its characters preserves the words, but not their relationship to the audio. Even an ordinary Codable round trip deserves a closer test: on the runtime used here, all 22 timed runs in a real recognition result lost their timing while the text survived.
We’ll save a small versioned transcript document with an explicit attribute scope, associate it with one immutable recording revision, and validate it before offering playback navigation. This builds on transcribing a file with SpeechAnalyzer; the focus here is what survives after recognition finishes.
Choose what the document preserves
This Stack Overflow question about missing custom attributes already has answers explaining configured coding. The mechanism isn’t new. The useful application is making a timed transcript survive reopening, rather than treating a successful JSON decode as proof that everything survived.
Natalia Panferova’s explanation of attribute scopes provides useful background. Alpay Calalli’s interactive transcript article preserves attributed substrings so taps can seek into a video. We’ll carry that preservation requirement across a save/load boundary.
The sample targets iOS 26 / macOS 26, using Swift 6.4.2 and Xcode 27.2 RC. Paste the three Swift blocks into one file in order, or download the complete verification sample. The persistence code needs no microphone permission or installed speech model; producing a new transcript still requires supported hardware, a supported locale and the appropriate assets.
Our scope includes Speech’s timing/confidence attributes and Foundation attributes such as links. It deliberately excludes display fonts and colors. Apple’s configured-coding APIs let us choose which attribute keys participate in serialization. Use the same scope on both sides.
import Foundation
import Speech
import CoreMedia
nonisolated struct TranscriptAttributes: AttributeScope {
let speech: AttributeScopes.SpeechAttributes
let foundation: AttributeScopes.FoundationAttributes
}
nonisolated struct TranscriptDocument: Codable {
let version: Int
let recordingRevision: UUID
let text: AttributedString
init(recordingRevision: UUID, text: AttributedString) {
self.version = 1
self.recordingRevision = recordingRevision
self.text = text
}
private enum CodingKeys: String, CodingKey {
case version, recordingRevision, text
}
init(from decoder: any Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
version = try values.decode(Int.self, forKey: .version)
guard version == 1 else {
throw DecodingError.dataCorruptedError(
forKey: .version, in: values,
debugDescription: "Unsupported transcript version"
)
}
recordingRevision = try values.decode(UUID.self, forKey: .recordingRevision)
text = try values.decode(
AttributedString.self, forKey: .text,
configuration: TranscriptAttributes.self
)
}
func encode(to encoder: any Encoder) throws {
var values = encoder.container(keyedBy: CodingKeys.self)
try values.encode(version, forKey: .version)
try values.encode(recordingRevision, forKey: .recordingRevision)
try values.encode(text, forKey: .text, configuration: TranscriptAttributes.self)
}
}
nonisolated keeps these value types independent of the project’s default actor isolation. The explicit coding methods also keep the document immutable. There is no hand-written JSON representation of CMTimeRange to maintain.
Treat the nested attribute encoding as Apple’s payload. This is an app-local document format, not a promised long-term interchange format or an SRT/WebVTT export. Keep saved fixtures in compatibility tests when changing supported OS versions or scopes. The outer version gives your app somewhere to introduce a migration; it doesn’t freeze Apple’s encoding.
Check which recording those times describe
The app assigns a revision UUID when it imports or records audio and keeps that revision immutable. Trimming, replacing or otherwise editing the audio creates a new revision. The same filename is not sufficient evidence that a timestamp still points to the same sound.
Load the expected revision and duration from your recording record, not from the transcript being checked. This UUID comparison catches accidental mismatches; it doesn’t inspect or authenticate the audio bytes. Your storage layer must enforce the immutable-revision rule.
Our document policy uses a zero-based file timeline. Timing ranges must be finite, nonnegative, within the recording, and have nondecreasing starts and ends. Repeated ranges and overlaps are permitted. Apple’s time-range lookup documentation requires ascending timing and explicitly permits gaps and untimed runs.
nonisolated struct RecordingTimeline {
let revision: UUID
let duration: CMTime
}
nonisolated enum TranscriptError: Error {
case wrongRecording, invalidTimeline, invalidTiming
case unorderedTiming, missingTiming, invalidConfidence, tooLarge
}
nonisolated extension TranscriptDocument {
func validate(for recording: RecordingTimeline) throws {
guard recordingRevision == recording.revision else {
throw TranscriptError.wrongRecording
}
let duration = recording.duration
guard duration.isNumeric, duration.timescale > 0,
duration.epoch == 0, duration >= .zero else {
throw TranscriptError.invalidTimeline
}
var previous: CMTimeRange?
var hasTiming = false
for run in text.runs {
if let confidence = run.transcriptionConfidence,
!confidence.isFinite || !(0...1).contains(confidence) {
throw TranscriptError.invalidConfidence
}
guard let range = run.audioTimeRange else { continue }
guard range.isValid,
range.start.isNumeric, range.duration.isNumeric,
range.start.timescale > 0, range.duration.timescale > 0,
range.start.epoch == 0, range.duration.epoch == 0,
range.start >= .zero, range.duration >= .zero,
range.end.isNumeric, range.end.timescale > 0,
range.end <= duration else {
throw TranscriptError.invalidTiming
}
if let previous,
range.start < previous.start || range.end < previous.end {
throw TranscriptError.unorderedTiming
}
previous = range
hasTiming = true
}
if !text.characters.isEmpty && !hasTiming {
throw TranscriptError.missingTiming
}
}
}
The positive-timescale checks matter: CMTime.isNumeric checks flags, so it does not by itself reject every malformed rational-time representation.
A run is a range of equal attributes, not necessarily one word. Styling can divide one spoken segment into several runs with identical timing. Spaces or punctuation may have no timing at all. Rejecting every untimed run would reject legitimate documents.
The last check catches complete timing loss in a nonempty transcript. It cannot prove every word was timed correctly, detect every partially stripped attribute, or judge recognition accuracy. An empty transcript is valid, including for audio that produced no recognized speech. A zero-duration timed range is also accepted, although it may not intersect a playback interval.
Save, reopen, then look up a passage
This small store writes one JSON file atomically and limits reads to 8 MiB plus one detection byte. That limit is an example product policy, not a Speech framework limit. A long recording may need a larger allowance or segmented documents.
These are synchronous file operations: run them on your app’s I/O worker, not inside a SwiftUI body or on the main actor during playback. The caller owns a valid parent directory, one writer per document and user-visible error handling. Atomic file replacement does not make the audio file and this JSON file a two-file transaction.
nonisolated enum TranscriptStore {
static let maximumBytes = 8 * 1_024 * 1_024
static func save(
_ document: TranscriptDocument,
for recording: RecordingTimeline,
to url: URL
) throws {
try document.validate(for: recording)
let data = try JSONEncoder().encode(document)
guard data.count <= maximumBytes else { throw TranscriptError.tooLarge }
try data.write(to: url, options: .atomic)
}
static func load(
from url: URL,
for recording: RecordingTimeline
) throws -> TranscriptDocument {
let file = try FileHandle(forReadingFrom: url)
defer { try? file.close() }
var data = Data()
while let chunk = try file.read(
upToCount: min(65_536, maximumBytes + 1 - data.count)
), !chunk.isEmpty {
data.append(chunk)
guard data.count <= maximumBytes else { throw TranscriptError.tooLarge }
}
let document = try JSONDecoder().decode(TranscriptDocument.self, from: data)
try document.validate(for: recording)
return document
}
}
Pass the final attributed text and its recording revision to TranscriptDocument, then call save. On reopening, use load with that recording’s timeline. Only enable timed navigation after this succeeds. A failure should leave the recording available and explain why timed navigation is unavailable; silently replacing a broken transcript with an empty one destroys useful evidence.
For playback highlighting, call document.text.rangeOfAudioTimeRangeAttributes(intersecting:) with the playback interval. It returns an optional range in that decoded attributed string. Use that range to style a display copy. Do not reuse an index from the pre-save string, and do not reconstruct attributed text from String(document.text.characters).
Keep final text separate from the presentation
Request .audioTimeRange in the transcriber’s attribute options. If you enable volatile results, display them separately and append only finalized results to the document. SpeechTranscriber.Result can report a phrase repeatedly while its interpretation changes; appending every revision would preserve the wrong thing very reliably.
The SpeechAnalyzer WWDC session demonstrates final and volatile transcript ownership. Our file-transcription walkthrough covers setup. The download includes a separate file-recognition probe so the persistence fixture can be regenerated.
Keep the original timed transcript as source data. Highlighting belongs in a display copy. User corrections need a separate representation or an explicit realignment policy: changing words while retaining their old timing attributes does not make those times accurate. This article doesn’t implement a subtitle editor or merge live recording sessions.
Test the metadata, not just the sentence
The verification sample compares complete attributed values and time-based lookups, writes to disk, and reopens the document in a separate process. Its controls deliberately remove the scope to reproduce the quiet failure.
| Check | Result in this fixture |
|---|---|
| Real file recognition on macOS, then ordinary attributed-string coding | Characters survived; 22 timed runs became zero |
| The same result with the explicit document scope | All 22 timed runs and interval lookups survived |
| Unicode, untimed punctuation, gaps and repeated timing | Preserved; lookup in a gap returned nil |
| Wrong recording revision, unknown version, wholly missing timing | Rejected before timed navigation |
| Invalid/out-of-bounds/unordered timing and invalid confidence | Rejected by the document policy |
| Missing, truncated and oversized files | Reported as failures, without overwriting the saved document |
The exact article code was compiled with Swift 6 warnings treated as errors, targeting iOS 26 and macOS 26, under ordinary and MainActor default isolation. Persistence and lookup checks also ran in the iOS 27 Simulator. Actual recognition used a generated speech file on macOS; the simulator loaded that fixture rather than proving iPhone recognition. No physical-device or older-OS round-trip claim is made.
The words passing a save/load test is a start. For a timed transcript, the useful test is whether the same passage still points into the same recording after the app comes back.