I am using the Android media library to sequentially play audio tracks. I would like to:
- Download the tracks only once
- Start playing the track as soon as enough data is available
- Start downloading a new track only when needed, ie when the previous track is completed
I've tried using a DownloadService as described here: https://developer.android.com/media/media3/exoplayer/downloading-media
However I am a bit confused on when to add new downloads. Note that I'm also using a MediaSessionService to enable background playback.
My current attempt is to create and add media items in this way:
val mediaItems = tracks.map { track ->
DownloadRequest.Builder(track.uri, Uri.parse(track.uri)).build()
downloadRequest.toMediaItem()
}
mediaController.setMediaItems(mediaItems, 0, 0)
And schedule the downloads listening to onMediaItemTransition in this way:
override fun onMediaItemTransition(mediaItem: MediaItem?, reason: Int) {
downloadRequest = // like above
DownloadService.sendAddDownload(
context, MediaDownloadService::class.java, downloadRequest, false)
However I think this will download the track twice, once by the DownloadService and once by the ExoPlayer as it will not find the cached track at first.
Any suggestions on how to do this right? Should the download of the track be handled directly in the MediaSessionService instead?