Merge pull request #1299 from Bnyro/master

don't block UI thread & fix crash when hls eq null
This commit is contained in:
Bnyro 2022-09-15 15:54:32 +02:00 committed by GitHub
commit 5c60bec2dc
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -34,7 +34,6 @@ import com.google.android.exoplayer2.audio.AudioAttributes
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
/**
* Loads the selected videos audio in background mode with a notification area.
@ -91,6 +90,8 @@ class BackgroundMode : Service() {
*/
private val autoplay = PreferenceHelper.getBoolean(PreferenceKeys.AUTO_PLAY, true)
private val handler = Handler(Looper.getMainLooper())
/**
* Setting the required [Notification] for running as a foreground service
*/
@ -129,7 +130,7 @@ class BackgroundMode : Service() {
autoPlayHelper = AutoPlayHelper(playlistId)
// play the audio in the background
playAudio(videoId, position)
loadAudio(videoId, position)
} catch (e: Exception) {
onDestroy()
}
@ -139,19 +140,28 @@ class BackgroundMode : Service() {
/**
* Gets the video data and prepares the [player].
*/
private fun playAudio(
private fun loadAudio(
videoId: String,
seekToPosition: Long = 0
) {
// append the video to the playing queue
Globals.playingQueue += videoId
runBlocking {
val job = launch {
CoroutineScope(Dispatchers.IO).launch {
try {
streams = RetrofitInstance.api.getStreams(videoId)
} catch (e: Exception) {
return@launch
}
// Wait until the job is done, to load correctly later in the player
job.join()
handler.post {
playAudio(seekToPosition)
}
}
}
private fun playAudio(
seekToPosition: Long
) {
initializePlayer()
setMediaItem()
@ -180,7 +190,6 @@ class BackgroundMode : Service() {
if (autoplay) setNextStream()
}
}
/**
* create the player
@ -244,7 +253,7 @@ class BackgroundMode : Service() {
// play new video on background
this.videoId = nextStreamId!!
this.segmentData = null
playAudio(videoId)
loadAudio(videoId)
}
/**
@ -252,7 +261,19 @@ class BackgroundMode : Service() {
*/
private fun setMediaItem() {
streams?.let {
val mediaItem = MediaItem.Builder().setUri(it.hls!!).build()
val uri = if (streams!!.hls != null) {
streams!!.hls
} else if (streams!!.audioStreams!!.isNotEmpty()) {
PlayerHelper.getAudioSource(
this,
streams!!.audioStreams!!
)
} else {
return
}
val mediaItem = MediaItem.Builder()
.setUri(uri)
.build()
player?.setMediaItem(mediaItem)
}
}