2022-05-08 16:11:08 +05:30
|
|
|
package com.github.libretube
|
|
|
|
|
|
|
|
import android.content.Context
|
|
|
|
import com.github.libretube.obj.Streams
|
|
|
|
import com.google.android.exoplayer2.ExoPlayer
|
|
|
|
import com.google.android.exoplayer2.MediaItem
|
|
|
|
import kotlinx.coroutines.launch
|
|
|
|
import kotlinx.coroutines.runBlocking
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Loads the selected video audio in background mode with a notification area.
|
|
|
|
*/
|
2022-05-20 01:43:42 +05:30
|
|
|
class BackgroundMode {
|
2022-05-08 16:11:08 +05:30
|
|
|
/**
|
|
|
|
* The response that gets when called the Api.
|
|
|
|
*/
|
|
|
|
private var response: Streams? = null
|
|
|
|
|
|
|
|
/**
|
|
|
|
* The [ExoPlayer] player. Followed tutorial [here](https://developer.android.com/codelabs/exoplayer-intro)
|
|
|
|
*/
|
|
|
|
private var player: ExoPlayer? = null
|
|
|
|
private var playWhenReadyPlayer = true
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Initializes the [player] player with the [MediaItem].
|
|
|
|
*/
|
2022-05-20 01:43:42 +05:30
|
|
|
private fun initializePlayer(c: Context) {
|
|
|
|
if (player == null) player = ExoPlayer.Builder(c).build()
|
|
|
|
setMediaItem()
|
2022-05-08 16:11:08 +05:30
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Releases the [player].
|
|
|
|
*/
|
|
|
|
private fun releasePlayer() {
|
2022-05-20 01:43:42 +05:30
|
|
|
player?.release()
|
2022-05-08 16:11:08 +05:30
|
|
|
player = null
|
|
|
|
}
|
|
|
|
|
2022-05-20 01:43:42 +05:30
|
|
|
/**
|
|
|
|
* Sets the [MediaItem] with the [response] into the [player].
|
|
|
|
*/
|
|
|
|
private fun setMediaItem() {
|
|
|
|
response?.let {
|
|
|
|
val mediaItem = MediaItem.fromUri(response!!.hls!!)
|
|
|
|
player?.setMediaItem(mediaItem)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-05-08 16:11:08 +05:30
|
|
|
/**
|
|
|
|
* Gets the video data and prepares the [player].
|
|
|
|
*/
|
2022-05-20 01:43:42 +05:30
|
|
|
fun playOnBackgroundMode(c: Context, videoId: String) {
|
2022-05-08 16:11:08 +05:30
|
|
|
runBlocking {
|
|
|
|
val job = launch {
|
|
|
|
response = RetrofitInstance.api.getStreams(videoId)
|
|
|
|
}
|
|
|
|
// Wait until the job is done, to load correctly later in the player
|
|
|
|
job.join()
|
|
|
|
|
2022-05-20 01:43:42 +05:30
|
|
|
initializePlayer(c)
|
2022-05-08 16:11:08 +05:30
|
|
|
|
|
|
|
player?.apply {
|
|
|
|
playWhenReady = playWhenReadyPlayer
|
|
|
|
prepare()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2022-05-20 01:43:42 +05:30
|
|
|
|
|
|
|
/**
|
|
|
|
* Creates a singleton of this class, to not create a new [player] every time.
|
|
|
|
*/
|
|
|
|
companion object {
|
|
|
|
private var INSTANCE: BackgroundMode? = null
|
|
|
|
|
|
|
|
fun getInstance(): BackgroundMode {
|
|
|
|
if (INSTANCE == null) INSTANCE = BackgroundMode()
|
|
|
|
return INSTANCE!!
|
|
|
|
}
|
|
|
|
}
|
2022-05-08 16:11:08 +05:30
|
|
|
}
|