Writing chapters to audio asset

I'm creating a Swift library for handling metadata tagging and adding/modifying chapters in .m4a/.m4b audio files. It's not intended to re-encode, so I need to be able to use the `AVAssetExportPresetPassthrough`.


I was doing fine with the metadata using AVAssetExportSession, but if there's a way to add an `[AVTimedMetadataGroup]` array to an export session, I haven't found it.


I've seen a lot of older posts in various places in regarding adding timed metadata to video and saving using AVAssetWriter in Objective-C, but I'm having trouble implementing them in Swift and I'm just not familiar with using AVAssetWriter. None of the methods I've tried have worked.


// get the source audio track
let audioTrack = asset.tracks(withMediaType: .audio).first
let audioDesc = audioTrack?.formatDescriptions as! CMFormatDescription

// turn it into an Input
let audioInput = AVAssetWriterInput(
    mediaType: .audio,
    outputSettings: nil,
    sourceFormatHint: audioDesc)

var writer = try AVAssetWriter(outputURL: outputUrl, fileType: .m4a)
var timedMetadata: [AVTimedMetadataGroup] = [...]

for group in timedMetadata {
    let desc = group.copyFormatDescription()
    // create text input
    let textInput = AVAssetWriterInput(mediaType: .text,
                                       outputSettings: nil,
                                       sourceFormatHint: desc)
    textInput.marksOutputTrackAsEnabled = false
    textInput.expectsMediaDataInRealTime = false
   
    let metadataAdaptor = AVAssetWriterInputMetadataAdaptor(
        assetWriterInput: textInput)
    textInput.requestMediaDataWhenReady(on: DispatchQueue(label: "metadataqueue", qos: .userInitiated), using: {
        metadataAdaptor.append(group)
    })
   
    if audioInput.canAddTrackAssociation(
        withTrackOf: textInput, type: AVAssetTrack.AssociationType.chapterList.rawValue) {
        audioInput.addTrackAssociation(
            withTrackOf: textInput, type: AVAssetTrack.AssociationType.chapterList.rawValue)
    }
   
    if writer.canAdd(textInput) {
        writer.add(textInput)
    }
}

if writer.canAdd(audioInput) {
    writer.add(audioInput)
}


So basically, where I'm starting out from, I've got an audio asset, an `[AVMetadataItem]` array, and an `[AVTimedMetadataGroup]` array, and I need to get them all into a single file at pass-through quality. I know what I have here is wrong, but I don't know how to fix it. Currently it writes a corrupt, zero-byte file.

I know this post is quite old, but have you been able to solve this problem? I'm in a similar situation. Thank you.

Writing chapters to audio asset
 
 
Q