定义Mediaplayer工具类 MediaplayerUtil
object MediaPlayerUtil {
private var mMediaPlayer : MediaPlayer ?= null
//数据源
private var data = mutableListOf<Url>()
//播放位置
private var position = -1
fun init() {
if (null == mMediaPlayer ) {
mMediaPlayer = MediaPlayer()
}
}
fun setData(data: MutableList<Url>) {
this.data = data
}
fun setDataSource() {
if ( !data.isNullOrEmpty() && position != -1 ) {
mMediaPlayer?.reset()
mMediaPlayer?.setDataSource(data[position])
mMediaPlayer?.prepareAsync()
}
}
fun startOrResumePlay() {
if ( mMediaPlayer.isPlaying ) {
mMediaPlayer?.pause()
} else {
mMediaPlayer?.start()
}
}
fun pauseOrResumePlay() {
if ( mMediaPlayer.isPlaying ) {
mMediaPlayer?.pause()
} else {
mMediaPlayer?.start()
}
}
fun stopPlay() {
mMediaPlayer?.stop()
}
fun getCurrentProgress() : Int? {
return mMediaPlayer?.currentPosition
}
fun getDuration() : Int? {
return mMediaPlayer?.duration
}
fun release() {
mMediaPlayer?.release()
mMediaPlayer = null
}
}