Files
AudioManagerClient/composeApp/src/androidMain/kotlin/win/taptap/musicmanager/client/MediaControllerAudioPlayer.kt
T
TapTap 8e737fae2e
CI / build (push) Successful in 3m59s
CI / play (push) Successful in 3m27s
fix: mirror a live service timeline after the UI is recreated
The media service can keep playing after the task is swiped. A new UI now
adopts its queue, index and position instead of showing a stale paused state.
Notification artwork also uses cached offline covers. Version 0.4.1.
2026-11-19 16:58:20 +00:00

213 lines
7.0 KiB
Kotlin

package win.taptap.musicmanager.client
import android.content.ComponentName
import android.content.Context
import android.net.Uri
import android.os.Bundle
import androidx.core.content.ContextCompat
import androidx.media3.common.MediaItem
import androidx.media3.common.MediaMetadata
import androidx.media3.common.Player
import androidx.media3.session.MediaController
import androidx.media3.session.SessionToken
import win.taptap.musicmanager.client.playback.AudioPlayer
import win.taptap.musicmanager.client.playback.PlaybackTrack
/**
* Client side of [PlaybackService]. The controller is created asynchronously;
* playback requests made before it connects are queued and executed once.
*/
class MediaControllerAudioPlayer(context: Context) : AudioPlayer {
private val appContext = context.applicationContext
private var controller: MediaController? = null
private val pending = ArrayDeque<(MediaController) -> Unit>()
private var connected = false
@Volatile private var finished = false
private val future = MediaController.Builder(
appContext,
SessionToken(appContext, ComponentName(appContext, PlaybackService::class.java)),
).buildAsync()
private val listener = object : Player.Listener {
override fun onPlaybackStateChanged(playbackState: Int) {
finished = playbackState == Player.STATE_ENDED
}
}
init {
future.addListener(
{
val sessionController = runCatching { future.get() }.getOrNull()
if (sessionController != null) {
controller = sessionController
sessionController.addListener(listener)
connected = true
val queued = synchronized(pending) {
pending.toList().also { pending.clear() }
}
queued.forEach { action -> runCatching { action(sessionController) } }
}
},
ContextCompat.getMainExecutor(appContext),
)
}
override fun setQueue(tracks: List<PlaybackTrack>, startIndex: Int, startAtSeconds: Double) {
if (tracks.isEmpty()) return
finished = false
val items = tracks.map(::mediaItem)
val index = startIndex.coerceIn(tracks.indices)
val positionMs = (startAtSeconds * 1_000).toLong().coerceAtLeast(0L)
withController { current ->
current.setMediaItems(items, index, positionMs)
current.prepare()
current.play()
}
}
override fun appendToQueue(tracks: List<PlaybackTrack>) {
if (tracks.isEmpty()) return
val items = tracks.map(::mediaItem)
withController { current -> current.addMediaItems(items) }
}
override fun moveInQueue(fromIndex: Int, toIndex: Int) {
withController { current -> current.moveMediaItem(fromIndex, toIndex) }
}
override fun removeAt(index: Int) {
withController { current -> current.removeMediaItem(index) }
}
override fun playIndex(index: Int, startAtSeconds: Double) {
finished = false
val positionMs = (startAtSeconds * 1_000).toLong().coerceAtLeast(0L)
withController { current ->
if (index in 0 until current.mediaItemCount) {
current.seekTo(index, positionMs)
current.play()
}
}
}
override fun skipToNext() {
withController { current -> current.seekToNextMediaItem() }
}
override fun skipToPrevious(restartAfterSeconds: Double) {
withController { current -> current.seekToPreviousMediaItem() }
}
override fun currentIndex(): Int = controller?.currentMediaItemIndex ?: 0
override fun queueSize(): Int = controller?.mediaItemCount ?: 0
override fun pause() {
withController { it.pause() }
}
override fun resume() {
withController { it.play() }
}
override fun stop() {
finished = false
withController {
it.stop()
it.clearMediaItems()
}
}
override fun isPlaying(): Boolean = controller?.isPlaying == true
override fun isFinished(): Boolean = finished
override fun positionSeconds(): Double =
(controller?.currentPosition ?: 0L).coerceAtLeast(0L) / 1000.0
override fun durationSeconds(): Double {
val duration = controller?.duration ?: 0L
return if (duration > 0) duration / 1000.0 else 0.0
}
override val canSeek: Boolean = true
override fun seekTo(seconds: Double) {
withController { it.seekTo((seconds * 1000).toLong().coerceAtLeast(0L)) }
}
override val supportsCrossfade: Boolean = true
override fun setCrossfadeSeconds(seconds: Int) {
val args = Bundle().apply { putInt(CROSSFADE_SECONDS, seconds.coerceAtLeast(0)) }
withController { current ->
runCatching { current.sendCustomCommand(CROSSFADE_COMMAND, args) }
}
}
override fun scheduleSleepTimer(seconds: Long?): Boolean {
val args = Bundle().apply { putLong(SLEEP_TIMER_SECONDS, seconds ?: 0L) }
val send: (MediaController) -> Unit = { current ->
runCatching { current.sendCustomCommand(SLEEP_TIMER_COMMAND, args) }
}
val current = controller
if (current != null && connected) {
send(current)
return true
}
synchronized(pending) { pending.addLast(send) }
return true
}
override fun release() {
controller?.release()
MediaController.releaseFuture(future)
controller = null
connected = false
synchronized(pending) { pending.clear() }
}
private fun mediaItem(track: PlaybackTrack): MediaItem {
val uri = if (track.local) {
Uri.fromFile(java.io.File(track.source))
} else {
Uri.parse(track.source)
}
val metadata = MediaMetadata.Builder()
.setTitle(track.song.title)
.setArtist(track.song.artist)
.setAlbumTitle(track.song.album)
.setExtras(
Bundle().apply { putDouble(GAIN_DB_KEY, track.gainDb ?: 0.0) },
)
.apply {
val bytes = track.artworkBytes
if (bytes != null && bytes.isNotEmpty()) {
setArtworkData(bytes, MediaMetadata.PICTURE_TYPE_FRONT_COVER)
} else if (!track.artworkUri.isNullOrBlank()) {
setArtworkUri(Uri.parse(track.artworkUri))
}
}
.build()
return MediaItem.Builder()
.setUri(uri)
.setMimeType("audio/mpeg")
.setMediaMetadata(metadata)
.build()
}
private fun withController(block: (MediaController) -> Unit) {
val current = controller
if (current != null && connected) {
block(current)
} else {
// The first playback request can be followed immediately by a seek.
// Keep every action, not only the last one.
synchronized(pending) { pending.addLast(block) }
}
}
}