44 lines
1.3 KiB
Kotlin
44 lines
1.3 KiB
Kotlin
package com.zhushenwudi.lovelivemusicplayer.player
|
|
|
|
import android.content.Context
|
|
import androidx.media3.common.AudioAttributes
|
|
import androidx.media3.common.C
|
|
import androidx.media3.exoplayer.ExoPlayer
|
|
|
|
/**
|
|
* [com.zhushenwudi.lovelivemusicplayer.player.PlayerController] 与 [com.zhushenwudi.lovelivemusicplayer.player.PlaybackService] MediaSession 共享的单一 ExoPlayer。
|
|
*/
|
|
object AndroidPlayerHolder {
|
|
@Volatile
|
|
private var player: ExoPlayer? = null
|
|
|
|
fun getOrCreate(context: Context): ExoPlayer {
|
|
player?.let { return it }
|
|
synchronized(this) {
|
|
player?.let { return it }
|
|
val created = ExoPlayer.Builder(context.applicationContext)
|
|
.setAudioAttributes(
|
|
AudioAttributes.Builder()
|
|
.setContentType(C.AUDIO_CONTENT_TYPE_MUSIC)
|
|
.setUsage(C.USAGE_MEDIA)
|
|
.build(),
|
|
/* handleAudioFocus = */ true,
|
|
)
|
|
// 有线/蓝牙耳机拔出或断开时暂停。
|
|
.setHandleAudioBecomingNoisy(true)
|
|
.build()
|
|
player = created
|
|
return created
|
|
}
|
|
}
|
|
|
|
fun get(): ExoPlayer? = player
|
|
|
|
fun release() {
|
|
synchronized(this) {
|
|
player?.release()
|
|
player = null
|
|
}
|
|
}
|
|
}
|