我想以编程方式导航 mp4 视频的章节。 这些章节在 QuickTime 中运行,所以我认为视频格式不是问题。
此页面中的代码应该返回一个章节数组,但只返回一个空数组: https://developer.apple.com/documentation/avfoundation/media_playback/presenting_chapter_markers
let asset = AVAsset(url: <# Asset URL #>)
let chapterLocalesKey = "availableChapterLocales"
asset.loadValuesAsynchronously(forKeys: [chapterLocalesKey]) {
var error: NSError?
let status = asset.statusOfValue(forKey: chapterLocalesKey, error: &error)
if status == .loaded {
let languages = Locale.preferredLanguages
let chapterMetadata = asset.chapterMetadataGroups(bestMatchingPreferredLanguages: languages)
// Process chapter metadata.
}
else {
// Handle other status cases.
}
}
有人知道怎么做吗?
func chapters(from avAsset: AVAsset) async -> [Chapter] {
guard let locales = try? await avAsset.load(.availableChapterLocales) else { return [] }
guard let locale = locales.first else { return [] }
guard let groups = try? await avAsset.loadChapterMetadataGroups(withTitleLocale: locale, containingItemsWithCommonKeys: [.commonKeyArtwork]) else { return [] }
return groups.map { group in
let titleItems = AVMetadataItem.metadataItems(from: group.items, filteredByIdentifier: .commonIdentifierTitle)
// Retrieve the artwork metadata items.
let artworkItems = AVMetadataItem.metadataItems(from: group.items, filteredByIdentifier: .commonIdentifierArtwork)
let title = titleItems.first?.stringValue ?? ""
let thumbnailData = artworkItems.first?.dataValue
return Chapter(cmTime: group.timeRange.start, title: title, thumbnailData: thumbnailData)
}
}