AudioPlayer.kt 12.7 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
16
import com.ydl.ydlcommon.utils.LogUtil
konghaorui committed
17
import com.yidianling.common.tools.ToastUtil
18 19
import tv.danmaku.ijk.media.player.IMediaPlayer
import tv.danmaku.ijk.media.player.IjkMediaPlayer
konghaorui committed
20 21 22 23 24 25 26
import java.io.IOException
import java.util.*
import kotlin.collections.ArrayList


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

    private var context: Context? = null
    private var audioFocusManager: AudioFocusManager? = null
33
    var mediaPlayer: IMediaPlayer? = null
konghaorui committed
34 35 36 37 38 39 40 41 42 43
    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) {
44 45 46 47 48
                val current = (mediaPlayer!!.currentPosition * 1.0).toFloat()
                val du = mediaPlayer!!.duration.toFloat()
                var percent = (current * 100 / du).toInt()
                //保存进度
                if (autoSaveProgress) {
49 50 51 52 53
                    PlayProgressUtil.saveProgress(
                        context,
                        playMusic!!.path,
                        (if (percent == 99 || percent == 100) 0 else current.toInt())
                    )
54
                }
konghaorui committed
55
                for (listener in listeners) {
徐健 committed
56
                    listener.onPublish(percent, current.toLong())
konghaorui committed
57 58 59 60 61 62 63
                }
            }
            handler!!.postDelayed(this, TIME_UPDATE)
        }
    }

    val audioSessionId: Int
konghaorui committed
64
        get() = if (mediaPlayer != null)mediaPlayer!!.audioSessionId else 0
konghaorui committed
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

    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
        }
97

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

    private object SingletonHolder {
        val instance = AudioPlayer()
    }

    /**
     * 初始化播放器
     */
    fun init(context: Context) {
        this.context = context.applicationContext
        audioFocusManager = AudioFocusManager(context)
122
        mediaPlayer = IjkMediaPlayer()
123 124 125 126 127 128 129 130 131 132
        try {
            (mediaPlayer as IjkMediaPlayer).setOption(
                IjkMediaPlayer.OPT_CATEGORY_FORMAT,
                "dns_cache_clear",
                1
            )
        } catch (e: Exception) {
            LogUtil.e(e.message)
        }

konghaorui committed
133 134
        mediaPlayer!!.setOnPreparedListener { mp ->
            if (isPreparing) {
135 136 137 138 139 140 141 142 143
                if (autoSaveProgress) {
                    //自动播放
                    var time = PlayProgressUtil.getProgress(context, playMusic!!.path)
                    if (time > 0) {
                        startPlayer()
                        seekTo(position = time.toLong())
                    } else {
                        startPlayer()
                    }
徐健 committed
144
                } else {
145 146 147 148 149
                    startPlayer()
                }
            }
            for (listener in listeners) {
                listener.onPrepared(mediaPlayer!!.duration)
konghaorui committed
150 151
            }
        }
徐健 committed
152
        mediaPlayer!!.setOnBufferingUpdateListener { mp, percent ->
konghaorui committed
153 154 155 156
            for (listener in listeners) {
                listener.onBufferingUpdate(percent)
            }
        }
徐健 committed
157
        mediaPlayer!!.setOnCompletionListener {
158 159 160 161
            if (autoSaveProgress) {
                PlayProgressUtil.saveProgress(applicationContext, playMusic!!.path, 0)
            }

konghaorui committed
162 163 164 165
            for (listener in listeners) {
                listener.onComplete()
            }

166 167 168 169 170
            if (playMode == PlayModeEnum.SINGLE) {
                stopPlayer()
                playMode = PlayModeEnum.LIST_LOOP
                return@setOnCompletionListener
            }
konghaorui committed
171

172 173 174 175 176 177
            next()
        }
        handler = Handler(Looper.getMainLooper())
        noisyReceiver = NoisyAudioStreamReceiver()
        noisyFilter = IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY)

konghaorui committed
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
    }

    /**
     * 添加播放监听
     */
    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)
205
        playMode = PlayModeEnum.LIST_LOOP
konghaorui committed
206
        autoSaveProgress = false
konghaorui committed
207 208 209 210 211
    }

    /**
     * 单曲模式播放音乐
     */
徐健 committed
212
    fun singlePlay(music: Music, isAutoSaveProgress: Boolean = false) {
konghaorui committed
213 214 215
        musicList.clear()
        musicList.add(music)
        playMode = PlayModeEnum.SINGLE
徐健 committed
216
        autoSaveProgress = isAutoSaveProgress
konghaorui committed
217 218 219
        play(0)
    }

徐健 committed
220 221 222 223 224 225 226 227 228 229 230
    /**
     * 单曲循环模式播放音乐
     */
    fun singleCirclePlay(music: Music) {
        musicList.clear()
        musicList.add(music)
        playMode = PlayModeEnum.SINGLE_LOOP
        autoSaveProgress = false
        play(0)
    }

konghaorui committed
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
    /**
     * 添加后自动播放
     */
    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)
    }

    /**
251
     * 加载指定索引的音乐
konghaorui committed
252 253 254 255 256 257 258 259 260 261 262 263 264 265
     */
    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
266

konghaorui committed
267 268 269 270
        val music = playMusic

        try {
            mediaPlayer!!.reset()
271
            mediaPlayer!!.dataSource = music!!.path
konghaorui committed
272 273 274 275 276
            mediaPlayer!!.prepareAsync()
            state = STATE_PREPARING
            for (listener in listeners) {
                listener.onChange(music)
            }
277
            if (isShowNotify) {
konghaorui committed
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 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
                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)
        }
    }

    /**
325
     *开始播放
konghaorui committed
326 327 328 329 330 331 332 333 334
     */
    fun startPlayer() {
        if (!isPreparing && !isPausing) {
            return
        }
        if (audioFocusManager!!.requestAudioFocus()) {
            mediaPlayer!!.start()
            state = STATE_PLAYING
            handler!!.post(mPublishRunnable)
335
            if (isShowNotify) {
konghaorui committed
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
                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)
358
        if (isShowNotify) {
359 360 361
            NotifyManager.get().showPause(playMusic)
            MediaSessionManager.get().updatePlaybackState()
        }
konghaorui committed
362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380
        context!!.unregisterReceiver(noisyReceiver)
        if (abandonAudioFocus) {
            audioFocusManager!!.abandonAudioFocus()
        }

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

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

        pausePlayer()
徐健 committed
381
        musicList.clear()
konghaorui committed
382 383 384 385 386 387 388 389 390 391 392
        mediaPlayer!!.reset()
        state = STATE_IDLE
    }

    /**
     * 下一首
     */
    operator fun next() {
        if (musicList.isEmpty()) {
            return
        }
393 394 395 396 397 398

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

        play(playPosition);
konghaorui committed
402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
    }

    /**
     * 上一首
     */
    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)
        }
    }

    /**
     * 跳转到指定的时间位置
421 422
     * @param percent 百分比
     * @param position 时间点
konghaorui committed
423
     */
徐健 committed
424
    fun seekTo(percent: Int = -1, position: Long = -1) {
konghaorui committed
425
        if (isPlaying || isPausing) {
426 427 428 429

            var currentPosition = 0L
            var currentPercent = 0

徐健 committed
430
            if (position != (-1).toLong()) {
431 432 433 434 435 436 437 438 439 440
                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
441
            MediaSessionManager.get().updatePlaybackState()
442
            if (autoSaveProgress) {
443 444 445 446 447
                PlayProgressUtil.saveProgress(
                    context,
                    musicList[playPosition].coverPath,
                    currentPosition.toInt()
                )
448
            }
konghaorui committed
449
            for (listener in listeners) {
徐健 committed
450
                listener.onPublish(currentPercent, currentPosition)
konghaorui committed
451 452 453 454 455 456 457 458 459 460 461
            }
        }
    }

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

462 463 464
    /**
     * 获取音乐时长
     */
徐健 committed
465 466
    fun getDuration(): Long {
        return mediaPlayer?.duration ?: 0
467 468
    }

konghaorui committed
469 470 471 472 473 474 475 476 477 478 479 480 481
    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
        }
    }
}