Skip to content

Instantly share code, notes, and snippets.

@SurajBahadur
Created November 30, 2022 06:20
Show Gist options
  • Save SurajBahadur/5b4de2e37566c0cf811a264d2aa92d51 to your computer and use it in GitHub Desktop.
Save SurajBahadur/5b4de2e37566c0cf811a264d2aa92d51 to your computer and use it in GitHub Desktop.
Fetch youtube URL for live stream
fun convertLinkToHls(youtubeLiveLink: String, activity: Activity) {
val hlsLink = arrayOf("")
val runnableCode = Runnable {
try {
val url = URL(youtubeLiveLink)
val con: HttpURLConnection = url.openConnection() as HttpURLConnection
con.requestMethod = "GET"
val `in` = BufferedReader(
InputStreamReader(con.inputStream)
)
var inputLine: String?
val content = StringBuffer()
while (`in`.readLine().also { inputLine = it } != null) {
content.append(inputLine)
}
`in`.close()
if (youtubeLiveLink.contains("m3u8")) {
hlsLink[0] = youtubeLiveLink
} else {
hlsLink[0] = extractHlsUrl(content.toString()).toString()
}
con.disconnect()
} catch (e: Exception) {
hlsLink[0] = youtubeLiveLink
e.printStackTrace()
Log.d(
"TAG", "convertLinkToHls: " +
": Reason is that the link is not a live url," +
"copy the link by open video then right click, copy video url from youtube."
)
}
}
val requestThread = Thread(runnableCode)
requestThread.start()
val timer = Timer()
timer.schedule(object : TimerTask() {
override fun run() {
if (!requestThread.isAlive) {
// hlsLink[0]
activity.runOnUiThread {
liveUrlLiveData.value = hlsLink[0]
}
/*runOnUiThread {
initializePlayer()
}*/
timer.cancel()
/* Here initialize the player,
* make you do it in runOnUiTHread() */
}
}
}, 1000, 1000)
}
private fun extractHlsUrl(response: String): String? {
val keyName = "hlsManifestUrl"
if (response.contains(keyName)) {
var index = response.indexOf(keyName)
index += 17
var lastIndex = index
while (lastIndex < response.length) {
if (response[lastIndex] == '8' &&
response[lastIndex - 1] == 'u' &&
response[lastIndex - 2] == '3' &&
response[lastIndex - 3] == 'm'
) {
break
}
lastIndex++
}
return response.substring(index, lastIndex + 1)
}
return null
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment