@cxm-2016
2016-09-19T11:37:36.000000Z
字数 1885
阅读 2764
android
Android中提供的MediaPlayer播放器并没有提供视频输出界面,所以我们需要使用SurfaceView来当做图像的输出界面。
使用步骤如下:
- 创建MediaPlayer对象,并加载视频文件
- 为SurfaceView的SurfaceHolder添加监听器CallBack
- 调用MediaPlayer对象的setDisplay(SurfaceHolder hd)将播放的视频图像输出到指定的SurfaceView(注意,此方法需要在SurfaceView被完全创建后调用,不然会抛出
The surface has been released
异常)
下列程序示例,这里千万注意setDisplay方法一定要在监听回调中调用,否则会由于SurfaceView并未完全创建而引发异常
class SMActivity : BaseActivity<IPresenter>() {
init {
orientation = Orientation.LANDSCAPE
}
val mp = MediaPlayer()
var isScroll = false
val loop = ThreadUtils.Loop(500).loop {
if (!isScroll)
smSeekBar.progress = mp.currentPosition
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_sm)
smStart.setOnClickListener { start() }
smPause.setOnClickListener { pause() }
smStop.setOnClickListener { stop() }
mp.setAudioStreamType(AudioManager.STREAM_MUSIC)
mp.setDataSource(video)
mp.prepare()
smSeekBar.max = mp.duration
smSeekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
}
override fun onStartTrackingTouch(seekBar: SeekBar?) {
isScroll = true
}
override fun onStopTrackingTouch(seekBar: SeekBar) {
mp.seekTo(seekBar.progress)
isScroll = false
}
})
smSurfaceView.holder.setKeepScreenOn(true)
smSurfaceView.holder.addCallback(object : SurfaceHolder.Callback {
override fun surfaceChanged(holder: SurfaceHolder?, format: Int, width: Int, height: Int) {
}
override fun surfaceDestroyed(holder: SurfaceHolder?) {
}
override fun surfaceCreated(holder: SurfaceHolder) {
//********************************************
mp.setDisplay(holder)//*******注意************
//********************************************
}
})
}
fun start() {
if (!mp.isPlaying) {
mp.start()
loop.start()
}
}
fun pause() {
if (mp.isPlaying) {
mp.pause()
}
}
fun stop() {
mp.stop()
loop.destroy()
}
override fun onDestroy() {
if (mp.isPlaying) stop()
mp.release()
super.onDestroy()
}
}