This is a fork of auramagi/SwiftWebVTT for added SPM support.
Swift WebVTT is a parser of WebVTT files that is based on a sample parser in the specification.
Originally written as part of Skipjack.
Functionality is currently limited to extracting a list of cues with their timings and text content. Extracting regions, stylesheets etc. is not implemented. Text styling such as bold, italics, ruby etc. is also not implemented.
As part of parsing text content of cues, this project implements a custom parser for HTML Character Entities based on the HTML 5.1 specification.
Saving files in WebVTT format and showing cues on screen is considered outside of scope of this project.
In the .xcodeproj
> General > Add Framework > Add Package Dependency > enter repo URL.
{...}
dependencies: [
// Dependencies declare other packages that this package depends on.
.package(url: "https://github.com/thisIsTheFoxe/SwiftWebVTT", from: "0.1.0")
],
{...}
For more details of the installation and usage of Swift Package Manager, visit its official website.
// Assuming `fileContents` is a `String` with WebVTT file data
let parser = WebVTTParser(string: fileContents)
let webVTT = try? parser.parse()
// webVTT?.cues holds an array of cues
YouTube has a different native format (SRV3) for captions, but their servers are able to convert to several different formats including WebVTT. However, for their ASR (automatic speech recognition) captions, YouTube bakes in a certain presentation that effectively duplicates cues.
This doesn't have a negative effect when presenting caption-by-caption, but makes content unreadable when extracting all text or just presenting all captions at once.
Swift WebVTT has a helper function to de-duplicate and reformat such files.
// var webVTT: WebVTT // A parsed file
let filteredCues = WebVTTParser.deduplicateCues(webVTT.cues)
webVTT = WebVTT(cues: filteredCues)
The custom parser for HTML Character References can also be used standalone to decode text with HTML entities.
let text = "Hello, world! 👋"
print(text.decodingHTMLEntities())
// > "Hello, world! 👋"
This implementation is reasonably fast and not memory-intensive. A ~1 MB file with 2h30m worth of captions loads in less than 1 second on an iPhone 7 Plus.
Swift WebVTT is available under the MIT license. See the LICENSE file for more info.