Android library to extract media files from YouTube. Library utilises Kotlin Coroutines and is built on top of Ktor client library as an extension function.
- Add network permission to your manifest:
<uses-permission android:name="android.permission.INTERNET" />
- Add this code snippet to your build.graddle or settings.gradle file:
Kotlin DSL:
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
google()
mavenCentral()
maven { setUrl("https://jitpack.io") } // <- add this
}
}
Groovy DSL:
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
google()
mavenCentral()
maven { url 'https://jitpack.io' } // <- add this
}
}
- Add the dependency to your app level build.gradle:
dependencies {
implementation("com.github.dinaraparanid:yt-url-extractor-kt:x.y.z.w")
}
dependencies {
implementation 'com.github.dinaraparanid:yt-url-extractor-kt:x.y.z.w'
}
- Create Ktor client:
private const val USER_AGENT =
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.98 Safari/537.36"
fun KtorClient() = HttpClient(OkHttp) {
install(UserAgent) {
agent = USER_AGENT
}
install(HttpRequestRetry)
install(HttpTimeout) {
connectTimeoutMillis = null
}
install(ContentNegotiation) {
json(Json { ignoreUnknownKeys = true })
}
install(Logging) {
logger = Logger.ANDROID
level = LogLevel.ALL
}
}
- Extract files by URL with an extension function:
val extractRes: Result<StreamData> = withTimeoutOrNull(timeMillis = 4500) {
ktorClient.extractYtFilesWithMeta(
context = context,
ytUrl = ytUrl
)
} ?: YtFailure(YtRequestTimeoutException())
val (
ytFiles: Map<Int, YtFile>, // Itag to media file
liveStreamManifestsRes: Result<LiveStreamManifests>, // DASH and HLS stream manifests
videoMetaRes: Result<VideoMeta> // Video metadata
) = when (val res = extractRes.getOrNull()) {
null -> onExtractionError(extractRes.exceptionOrNull()!!)
else -> res
}
val videoMeta: VideoMeta = when (val res = videoMetaRes.getOrNull()) {
null -> onExtractionError(videoMetaRes.exceptionOrNull()!!)
else -> res
}
val liveStreamManifests = when (val res = liveStreamManifestsRes.getOrNull()) {
null -> onExtractionError(liveStreamManifestsRes.exceptionOrNull()!!)
else -> res
}
// Extract desired url (e.g. itag = 140 for audio files)
val audioUrl: String? = when (videoMeta?.isLiveStream) {
true -> liveStreamManifests.hlsManifestUrl
else -> ytFiles[DEFAULT_AUDIO_TAG]?.url
}
if (audioUrl == null)
onExtractionError(YtFilesNotFoundException())
Android 5.0 or higher
GNU Public License V 3.0