AudioPlayer.kt 12.2 KB
Newer Older
konghaorui committed
1
package com.ydl.media.audio
konghaorui committed
2 3 4 5 6 7

import android.content.Context
import android.content.IntentFilter
import android.media.AudioManager
import android.os.Handler
import android.os.Looper
8
import com.tencent.bugly.Bugly.applicationContext
konghaorui committed
9 10 11 12 13 14 15
import com.ydl.media.audio.enums.PlayModeEnum
import com.ydl.media.audio.manager.AudioFocusManager
import com.ydl.media.audio.manager.MediaSessionManager
import com.ydl.media.audio.manager.NotifyManager
import com.ydl.media.audio.model.Music
import com.ydl.media.audio.receiver.NoisyAudioStreamReceiver
import com.ydl.media.audio.utils.PlayProgressUtil
konghaorui committed
16
import com.yidianling.common.tools.ToastUtil
17 18
import tv.danmaku.ijk.media.player.IMediaPlayer
import tv.danmaku.ijk.media.player.IjkMediaPlayer
konghaorui committed
19 20 21 22 23 24 25
import java.io.IOException
import java.util.*
import kotlin.collections.ArrayList


/**
 * Created by haorui on 2019-10-27 .
徐健 committed
26
 * Des:
konghaorui committed
27 28 29 30 31
 */
class AudioPlayer private constructor() {

    private var context: Context? = null
    private var audioFocusManager: AudioFocusManager? = null
32
    var mediaPlayer: IMediaPlayer? = null
konghaorui committed
33 34 35 36 37 38 39 40 41 42
    private var handler: Handler? = null
    private var noisyReceiver: NoisyAudioStreamReceiver? = null
    private var noisyFilter: IntentFilter? = null
    private var musicList: MutableList<Music> = ArrayList()
    private val listeners = ArrayList<OnPlayerEventListener>()
    private var state = STATE_IDLE

    private val mPublishRunnable = object : Runnable {
        override fun run() {
            if (isPlaying) {
43 44 45 46 47
                val current = (mediaPlayer!!.currentPosition * 1.0).toFloat()
                val du = mediaPlayer!!.duration.toFloat()
                var percent = (current * 100 / du).toInt()
                //保存进度
                if (autoSaveProgress) {
徐健 committed
48
                    PlayProgressUtil.saveProgress(context, playMusic!!.path, (if (percent == 99 || percent == 100) 0 else current.toInt()))
49
                }
konghaorui committed
50
                for (listener in listeners) {
徐健 committed
51
                    listener.onPublish(percent, current.toLong())
konghaorui committed
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
                }
            }
            handler!!.postDelayed(this, TIME_UPDATE)
        }
    }

    val audioSessionId: Int
        get() = mediaPlayer!!.audioSessionId

    val audioPosition: Long
        get() = if (isPlaying || isPausing) {
            mediaPlayer!!.currentPosition.toLong()
        } else {
            0
        }

    val playMusic: Music?
        get() = if (musicList.isEmpty()) {
            null
        } else musicList[playPosition]

    val isPlaying: Boolean
        get() = state == STATE_PLAYING

    val isPausing: Boolean
        get() = state == STATE_PAUSE

    val isPreparing: Boolean
        get() = state == STATE_PREPARING

    val isIdle: Boolean
        get() = state == STATE_IDLE

    var playPosition: Int = 0
        get() {
            if (field < 0 || field >= musicList.size) {
                field = 0
            }
            return field
        }
92

konghaorui committed
93 94 95 96 97
    /**
     * 设置播放模式
     * 默认为列表循环
     */
    var playMode = PlayModeEnum.LIST_LOOP
98 99 100 101
    /**
     * 是否自动保存播放进度
     */
    var autoSaveProgress = false
102 103 104 105
    /**
     * 是否显示通知栏
     */
    var isShowNotify = false
konghaorui committed
106 107 108 109 110 111 112 113 114 115 116

    private object SingletonHolder {
        val instance = AudioPlayer()
    }

    /**
     * 初始化播放器
     */
    fun init(context: Context) {
        this.context = context.applicationContext
        audioFocusManager = AudioFocusManager(context)
117
        mediaPlayer = IjkMediaPlayer()
konghaorui committed
118 119
        mediaPlayer!!.setOnPreparedListener { mp ->
            if (isPreparing) {
120 121 122 123 124 125 126 127 128
                if (autoSaveProgress) {
                    //自动播放
                    var time = PlayProgressUtil.getProgress(context, playMusic!!.path)
                    if (time > 0) {
                        startPlayer()
                        seekTo(position = time.toLong())
                    } else {
                        startPlayer()
                    }
徐健 committed
129
                } else {
130 131 132 133 134
                    startPlayer()
                }
            }
            for (listener in listeners) {
                listener.onPrepared(mediaPlayer!!.duration)
konghaorui committed
135 136
            }
        }
徐健 committed
137
        mediaPlayer!!.setOnBufferingUpdateListener { mp, percent ->
konghaorui committed
138 139 140 141
            for (listener in listeners) {
                listener.onBufferingUpdate(percent)
            }
        }
徐健 committed
142
        mediaPlayer!!.setOnCompletionListener {
143 144 145 146
            if (autoSaveProgress) {
                PlayProgressUtil.saveProgress(applicationContext, playMusic!!.path, 0)
            }

konghaorui committed
147 148 149 150
            for (listener in listeners) {
                listener.onComplete()
            }

151 152 153 154 155
            if (playMode == PlayModeEnum.SINGLE) {
                stopPlayer()
                playMode = PlayModeEnum.LIST_LOOP
                return@setOnCompletionListener
            }
konghaorui committed
156

157 158 159 160 161 162
            next()
        }
        handler = Handler(Looper.getMainLooper())
        noisyReceiver = NoisyAudioStreamReceiver()
        noisyFilter = IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY)

konghaorui committed
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
    }

    /**
     * 添加播放监听
     */
    fun addOnPlayEventListener(listener: OnPlayerEventListener) {
        if (!listeners.contains(listener)) {
            listeners.add(listener)
        }
    }

    /**
     * 移除播放监听
     */
    fun removeOnPlayEventListener(listener: OnPlayerEventListener) {
        listeners.remove(listener)
    }

    /**
     * 添加播放列表
     */
    fun addPlayList(music: ArrayList<Music>) {
        if (music.isEmpty()) {
            return
        }
        musicList.clear()
        musicList.addAll(music)
190
        playMode = PlayModeEnum.LIST_LOOP
konghaorui committed
191
        autoSaveProgress = false
konghaorui committed
192 193 194 195 196
    }

    /**
     * 单曲模式播放音乐
     */
徐健 committed
197
    fun singlePlay(music: Music, isAutoSaveProgress: Boolean = false) {
konghaorui committed
198 199 200
        musicList.clear()
        musicList.add(music)
        playMode = PlayModeEnum.SINGLE
徐健 committed
201
        autoSaveProgress = isAutoSaveProgress
konghaorui committed
202 203 204
        play(0)
    }

徐健 committed
205 206 207 208 209 210 211 212 213 214 215
    /**
     * 单曲循环模式播放音乐
     */
    fun singleCirclePlay(music: Music) {
        musicList.clear()
        musicList.add(music)
        playMode = PlayModeEnum.SINGLE_LOOP
        autoSaveProgress = false
        play(0)
    }

konghaorui committed
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
    /**
     * 添加后自动播放
     */
    fun addAndPlay(music: Music) {
        var position = musicList.indexOf(music)
        if (position < 0) {
            musicList.add(music)
            position = musicList.size - 1
        }
        play(position)
    }

    /**
     * 播放第一首
     */
    fun play() {
        play(0)
    }

    /**
236
     * 加载指定索引的音乐
konghaorui committed
237 238 239 240 241 242 243 244 245 246 247 248 249 250
     */
    fun play(position: Int) {
        var position = position
        if (musicList.isEmpty()) {
            return
        }

        if (position < 0) {
            position = musicList.size - 1
        } else if (position >= musicList.size) {
            position = 0
        }

        playPosition = position
251

konghaorui committed
252 253 254 255
        val music = playMusic

        try {
            mediaPlayer!!.reset()
256
            mediaPlayer!!.dataSource = music!!.path
konghaorui committed
257 258 259 260 261
            mediaPlayer!!.prepareAsync()
            state = STATE_PREPARING
            for (listener in listeners) {
                listener.onChange(music)
            }
262
            if (isShowNotify) {
konghaorui committed
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
                NotifyManager.get().showPlay(music)
                MediaSessionManager.get().updateMetaData(music)
                MediaSessionManager.get().updatePlaybackState()
            }
        } catch (e: IOException) {
            e.printStackTrace()
            ToastUtil.toastShort("当前歌曲无法播放")
        }

    }

    /**
     * 从列表里移除播放音乐
     */
    fun delete(position: Int) {
        val music = musicList!!.removeAt(position)
        if (playPosition > position) {
            playPosition -= 1
        } else if (playPosition == position) {
            if (isPlaying || isPreparing) {
                playPosition -= 1
                next()
            } else {
                stopPlayer()
                for (listener in listeners) {
                    listener.onChange(playMusic!!)
                }
            }
        }
    }

    /**
     * 暂停或者播放音乐
     */
    fun playPause() {
        if (isPreparing) {
            stopPlayer()
        } else if (isPlaying) {
            pausePlayer()
        } else if (isPausing) {
            startPlayer()
        } else {
            play(playPosition)
        }
    }

    /**
310
     *开始播放
konghaorui committed
311 312 313 314 315 316 317 318 319
     */
    fun startPlayer() {
        if (!isPreparing && !isPausing) {
            return
        }
        if (audioFocusManager!!.requestAudioFocus()) {
            mediaPlayer!!.start()
            state = STATE_PLAYING
            handler!!.post(mPublishRunnable)
320
            if (isShowNotify) {
konghaorui committed
321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
                NotifyManager.get().showPlay(playMusic)
                MediaSessionManager.get().updatePlaybackState()
            }
            context!!.registerReceiver(noisyReceiver, noisyFilter)
            for (listener in listeners) {
                listener.onPlayerStart()
            }
        }
    }

    /**
     * 暂停播放器
     */
    @JvmOverloads
    fun pausePlayer(abandonAudioFocus: Boolean = true) {
        if (!isPlaying) {
            return
        }

        mediaPlayer!!.pause()
        state = STATE_PAUSE
        handler!!.removeCallbacks(mPublishRunnable)
343 344 345 346
        if(isShowNotify){
            NotifyManager.get().showPause(playMusic)
            MediaSessionManager.get().updatePlaybackState()
        }
konghaorui committed
347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365
        context!!.unregisterReceiver(noisyReceiver)
        if (abandonAudioFocus) {
            audioFocusManager!!.abandonAudioFocus()
        }

        for (listener in listeners) {
            listener.onPlayerPause()
        }
    }

    /**
     * 停止播放器
     */
    fun stopPlayer() {
        if (isIdle) {
            return
        }

        pausePlayer()
徐健 committed
366
        musicList.clear()
konghaorui committed
367 368 369 370 371 372 373 374 375 376 377
        mediaPlayer!!.reset()
        state = STATE_IDLE
    }

    /**
     * 下一首
     */
    operator fun next() {
        if (musicList.isEmpty()) {
            return
        }
378 379 380 381 382 383

        var playPosition = when (playMode) {
            PlayModeEnum.SHUFFLE -> Random().nextInt(musicList.size)
            PlayModeEnum.SINGLE_LOOP -> playPosition
            PlayModeEnum.LIST_LOOP -> playPosition + 1
            else -> playPosition + 1
konghaorui committed
384
        }
385 386

        play(playPosition);
konghaorui committed
387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405
    }

    /**
     * 上一首
     */
    fun prev() {
        if (musicList.isEmpty()) {
            return
        }
        when (playMode) {
            PlayModeEnum.SHUFFLE -> play(Random().nextInt(musicList.size))
            PlayModeEnum.SINGLE_LOOP -> play(playPosition)
            PlayModeEnum.LIST_LOOP -> play(playPosition - 1)
            else -> play(playPosition - 1)
        }
    }

    /**
     * 跳转到指定的时间位置
406 407
     * @param percent 百分比
     * @param position 时间点
konghaorui committed
408
     */
徐健 committed
409
    fun seekTo(percent: Int = -1, position: Long = -1) {
konghaorui committed
410
        if (isPlaying || isPausing) {
411 412 413 414

            var currentPosition = 0L
            var currentPercent = 0

徐健 committed
415
            if (position != (-1).toLong()) {
416 417 418 419 420 421 422 423 424 425
                val current = (currentPosition * 1.0).toFloat()
                val du = mediaPlayer!!.duration.toFloat()
                currentPercent = (current * 100 / du).toInt()

                currentPosition = position
            } else {
                currentPosition = percent * mediaPlayer!!.duration / 100
            }

            mediaPlayer!!.seekTo(currentPosition)
konghaorui committed
426
            MediaSessionManager.get().updatePlaybackState()
427 428 429
            if (autoSaveProgress) {
                PlayProgressUtil.saveProgress(context, musicList[playPosition].coverPath, currentPosition.toInt())
            }
konghaorui committed
430
            for (listener in listeners) {
徐健 committed
431
                listener.onPublish(currentPercent, currentPosition)
konghaorui committed
432 433 434 435 436 437 438 439 440 441 442
            }
        }
    }

    /**
     * 获取播放列表
     */
    fun getMusicList(): List<Music>? {
        return musicList
    }

443 444 445
    /**
     * 获取音乐时长
     */
徐健 committed
446 447
    fun getDuration(): Long {
        return mediaPlayer?.duration ?: 0
448 449
    }

konghaorui committed
450 451 452 453 454 455 456 457 458 459 460 461 462
    companion object {
        private val STATE_IDLE = 0
        private val STATE_PREPARING = 1
        private val STATE_PLAYING = 2
        private val STATE_PAUSE = 3

        private val TIME_UPDATE = 300L

        fun get(): AudioPlayer {
            return SingletonHolder.instance
        }
    }
}