I tried to find a library that fetches YouTube video transcripts for Swift but couldn’t find one, so I made one myself.
This package uses an unofficial YouTube API, so it may break over time if no updates are made. The library uses an HTML scraper and the Innertube API to fetch transcripts.
Heavily inspired by youtube-transcript
- Fetches transcripts for YouTube videos and Shorts
- Supports language selection
- Handles all major YouTube transcript error cases
- Async/await API for modern Swift concurrency
- Comprehensive unit tests using Swift Testing
Library using one simple function to fetch transcript
fetchTranscript(for videoId: String,config: TranscriptConfig = .init()) async throws -> [TranscriptResponse]
import YoutubeTranscript
Task {
do {
let transcript = try await YoutubeTranscript.fetchTranscript(for: "YOUR_VIDEO_ID")
for entry in transcript {
print("\(entry.offset)s: \(entry.text)")
}
} catch {
print("Failed to fetch transcript: \(error)")
}
}
let config = TranscriptConfig(lang: "en")
let transcript = try await YoutubeTranscript.fetchTranscript(for: "YOUR_VIDEO_ID", config: config)
- Standard videos:
https://www.youtube.com/watch?v=VIDEO_ID
- Short URLs:
https://youtu.be/VIDEO_ID
- YouTube Shorts:
https://www.youtube.com/shorts/VIDEO_ID
- Embedded videos:
https://www.youtube.com/embed/VIDEO_ID
- Direct video IDs:
VIDEO_ID
The library throws YoutubeTranscriptError
for all error cases:
.tooManyRequests
: YouTube is rate-limiting your IP.videoUnavailable
: The video is not available.disabled
: Transcripts are disabled for this video.notAvailable
: No transcripts are available.notAvailableLanguage
: No transcript in the requested language.emptyTranscript
: The transcript is empty.invalidVideoId
: The video ID is invalid.networkError
: Network error occurred.parsingError
: Failed to parse YouTube response
- macOS 12.0+
- iOS 15.0+
- tvOS 15.0+
- watchOS 8.0+
Add this package to your Package.swift
dependencies:
.package(url: "https://github.com/spaceman1412/swift-youtube-transcript.git", from: "1.0.0")
And add YoutubeTranscript
as a dependency for your target:
.target(
name: "<target>",
dependencies: [
.product(name: "YoutubeTranscript", package: "swift-youtube-transcript")
]
)
- From the File menu, select Add Packages…
- Enter
https://github.com/spaceman1412/swift-youtube-transcript
into the Search or Enter Package URL search field - Link YoutubeTranscript to your application target
This project uses Swift Testing for its test suite.
To run the tests:
swift test
The tests cover all major success and error cases for fetchTranscript
. You can provide your own video IDs in Tests/YoutubeTranscriptTests.swift
to verify real-world scenarios.
MIT