日常開發(fā)中适掰,我們一般使用MediaPlayer來快速實現音頻的播放颂碧。
但是功能實在有限,最近遇到一個需求类浪,需要控制音頻的播放速度载城、音調。
用MediaPlayer只能干瞪眼费就,實在沒轍诉瓦,做不到啊。
ExoPlayer
ExoPlayer is an application level media player for Android. It provides an alternative to Android’s MediaPlayer API for playing audio and video both locally and over the Internet. ExoPlayer supports features not currently supported by Android’s MediaPlayer API, including DASH and SmoothStreaming adaptive playbacks. Unlike the MediaPlayer API, ExoPlayer is easy to customize and extend, and can be updated through Play Store application updates.
簡介中的這前兩句話,明確說明ExoPlayer是用來替代MediaPlayer的睬澡。
看來以后再遇到音視頻相關的功能固额,直接上ExoPlayer就好啦。
話不多說煞聪,直接進入主題:用ExoPlayer先播放個音頻看看效果斗躏。
添加依賴,接入到項目中
這里不做贅述昔脯,直接看文檔:https://exoplayer.dev/hello-world.html
播放個音頻
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
btn_play.setOnClickListener {
play(radioUrl = Uri.fromFile(File("/sdcard/care.mp3")))
}
}
private fun play(radioUrl: Uri) {
//創(chuàng)建exoPlayer實例
val player = ExoPlayerFactory.newSimpleInstance(this)
val dataSourceFactory = DefaultDataSourceFactory(
this,
Util.getUserAgent(this, application.packageName)
)
//創(chuàng)建mediaSource
val mediaSource = ProgressiveMediaSource.Factory(dataSourceFactory)
.createMediaSource(radioUrl)
//準備播放
player.prepare(mediaSource)
//設置播放速度和音調均為2倍速
player.playbackParameters = PlaybackParameters(2.0f, 2.0f)
//資源加載后立即播放
player.playWhenReady = true
}
}
play()方法就簡單實現了播放本地mp3文件瑟捣,并且設置了播放速度和音調均為2倍。效果不錯栅干!
獲取播放狀態(tài)
val state = player.playWhenReady
控制播放和暫停
- 暫停播放
player.playWhenReady = false
- 開始播放
player.playWhenReady = true
獲取媒體資源的時長
//給mediaSsource添加監(jiān)聽器迈套,當媒體資源加載完成后,會回調onLoadCompleted方法
mediaSource?.addEventListener(mHandler, object : DefaultMediaSourceEventListener() {
override fun onLoadCompleted(windowIndex: Int, mediaPeriodId: MediaSource.MediaPeriodId?,
loadEventInfo: MediaSourceEventListener.LoadEventInfo?,
mediaLoadData: MediaSourceEventListener.MediaLoadData?) {
//移除監(jiān)聽器碱鳞,避免重復回調
mediaSource.removeEventListener(this)
val duration = player.duration.toInt()
seekBar.max = duration
}
})
監(jiān)聽播放器的狀態(tài)
player.addListener(object : Player.EventListener {
override fun onPlayerStateChanged(playWhenReady: Boolean, playbackState: Int) {
when (playbackState) {
Player.STATE_IDLE -> {
Log.i(TAG, "STATE_IDLE")
}
Player.STATE_BUFFERING -> {
Log.i(TAG, "STATE_BUFFERING")
}
Player.STATE_READY -> {
Log.i(TAG, "STATE_READY")
}
Player.STATE_ENDED -> {
Log.i(TAG, "STATE_ENDED")
}
}
}
})
控制循環(huán)播放
val loopResource = LoopingMediaSource(mediaSource)
player.prepare(loopResource)