fix
lmw
2025-03-04 449bdb5d2b5bf7b272ca5cda4c066f9a65040064
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
package com.sinata.xqmuse
 
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Intent
import android.media.AudioManager
import android.media.MediaPlayer
import android.os.Build
import android.os.IBinder
import android.os.PowerManager
import android.util.Log
import androidx.core.app.NotificationCompat
import cn.sinata.xldutils.utils.SPUtils
import com.sinata.xqmuse.network.entity.VoiceDetail
import com.sinata.xqmuse.utils.AudioUtils
import com.sinata.xqmuse.utils.Const
import com.sinata.xqmuse.utils.event.EmptyEvent
import com.sinata.xqmuse.utils.event.IntEvent
import kotlinx.android.synthetic.main.activity_main.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
 
class ThinkAudioService:Service(), AudioUtils.OnAudioStatusUpdateListener {
    private var thinkBgPlayer: AudioUtils? = null//冥想背景音播放器
    private var wakeLock: PowerManager.WakeLock? = null
    private val TAG = "ThinkAudioService"
 
    override fun onCreate() {
        super.onCreate()
        EventBus.getDefault().register(this)
        Log.e(TAG,"ThinkAudioService初始化")
        // 初始化 MediaPlayer
        if (thinkBgPlayer == null){
            thinkBgPlayer = AudioUtils()
            thinkBgPlayer!!.setOnAudioStatusUpdateListener(this)
        }
 
        // 初始化 WakeLock
        val powerManager = getSystemService(POWER_SERVICE) as PowerManager
        wakeLock = powerManager.newWakeLock(
            PowerManager.PARTIAL_WAKE_LOCK,
            "AudioService::WakeLock"
        )
    }
 
    private val focusChangeListener =
        AudioManager.OnAudioFocusChangeListener { focusChange ->
            if (focusChange == AudioManager.AUDIOFOCUS_LOSS) {
                thinkBgPlayer?.pause() // 焦点丢失时暂停播放
            }
        }
 
    private fun createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                "audio_channel",
                "音频播放",
                NotificationManager.IMPORTANCE_LOW
            )
            getSystemService(NotificationManager::class.java).createNotificationChannel(channel)
        }
    }
 
    override fun onBind(intent: Intent?): IBinder? {
        return null
    }
 
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        // 创建通知渠道(Android 8.0+ 必须)
        createNotificationChannel()
 
        // 启动前台服务
        val notification = NotificationCompat.Builder(this, "audio_channel")
            .setContentTitle("正在疗愈")
            .setSmallIcon(R.mipmap.ic_launcher)
            .build()
        startForeground(1, notification)
 
        // 请求音频焦点 todo 请求焦点会导致首页水波纹视频暂停
//        val audioManager = getSystemService(AUDIO_SERVICE) as AudioManager
//        val result = audioManager.requestAudioFocus(
//            focusChangeListener,
//            AudioManager.STREAM_MUSIC,
//            AudioManager.AUDIOFOCUS_GAIN
//        )
//        if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
            val volume = SPUtils.instance().getInt(Const.User.VOLUME_THINK, 50)
            thinkBgPlayer?.setVolume(volume.toFloat() / 100)
            thinkBgPlayer?.startPlayMusic(this, voice?.meditationMusicList?.get(index))
            wakeLock?.acquire(60 * 60 * 1000L) // 申请 WakeLock
//        }
        return START_STICKY
    }
 
    @Subscribe
    fun onAudioEvent(e: EmptyEvent){
        when(e.code){
            Const.EventCode.SERVICE_AUDIO_PAUSE->{
                thinkBgPlayer?.pause()
            }
            Const.EventCode.SERVICE_AUDIO_RESUME->{
                thinkBgPlayer?.resume()
            }
            Const.EventCode.CHANGE_THINK_VOLUME->{
                val v = SPUtils.instance().getInt(Const.User.VOLUME_THINK, 50)
                thinkBgPlayer?.setVolume(v.toFloat() / 100)
            }
            Const.EventCode.SERVICE_AUDIO_PROGRESS->{
                currentPosition = thinkBgPlayer?.currentPosition ?: 0
                EventBus.getDefault().post(EmptyEvent(Const.EventCode.GOT_THINK_POSITION))
            }
        }
    }
 
    @Subscribe
    fun onIntEvent(e: IntEvent){
        if (e.code == Const.EventCode.SERVICE_AUDIO_SEEK){
            thinkBgPlayer?.seekTo(e.i)
        }
    }
 
    override fun onDestroy() {
        EventBus.getDefault().unregister(this)
        thinkBgPlayer?.stopPlayMusic(false)
        if (wakeLock != null && wakeLock!!.isHeld) {
            wakeLock!!.release()
        }
        super.onDestroy()
    }
 
    override fun onUpdate(db: Double, time: Long) {
 
    }
 
    override fun onStop(filePath: String?) {
    }
 
    override fun onStartPlay() {
    }
 
    override fun onFinishPlay() {
        if (voice == null) //说明是手动关闭的,不需要处理下一步播放逻辑
            return
        if (isRecycle){ //单曲
            if (playing)
                thinkBgPlayer?.startPlayMusic(this, voice?.meditationMusicList?.get(index))
        }else{//顺序
            index++
            if (index>=voice?.meditationMusicList?.size?:0)//列表已播完
                EventBus.getDefault().post(EmptyEvent(Const.EventCode.FINISH_THINK))
            else{
                currentDuration = voice?.meditationSecondList?.get(index)?:0
                EventBus.getDefault().post(EmptyEvent(Const.EventCode.GOT_THINK_DURATION))
                if (playing)
                    thinkBgPlayer?.startPlayMusic(this, voice?.meditationMusicList?.get(index))
            }
        }
    }
 
    override fun onGetDuration(duration: Int) {
    }
 
    companion object{ //冥想播放相关参数
        var playing = false //true播放中
        var isRecycle = false //true单曲循环播放
        var voice: VoiceDetail? = null //冥想详情
        var index = 0 //当前播放序号
        var currentDuration = 0 //当前音频长度(秒)
        var currentPosition = 0L //当前音频进度(毫秒)
        var finishTime = 0L //自动结束的时间戳
    }
}