MediaController簡介
官方API 文檔
MediaController | Android Developers
使用demo
Android自帶的MediaController實現網絡播放和本地播放
結合VideoView和MediaController的例子簡單介紹下
base/core/java/android/widget/VideoView.java
public class VideoView extends SurfaceView
implements MediaPlayerControl, SubtitleController.Anchor {
// ....
// MediaPlayerControl 接口類方法實現
@Override
public void start() {
if (isInPlaybackState()) {
mMediaPlayer.start();
mCurrentState = STATE_PLAYING;
}
mTargetState = STATE_PLAYING;
}
public void setMediaController(MediaController controller) {
if (mMediaController != null) {
mMediaController.hide();
}
mMediaController = controller;
attachMediaController();
}
private void attachMediaController() {
if (mMediaPlayer != null && mMediaController != null) {
mMediaController.setMediaPlayer(this);
View anchorView = this.getParent() instanceof View ?
(View)this.getParent() : this;
mMediaController.setAnchorView(anchorView);
mMediaController.setEnabled(isInPlaybackState());
}
}
}
可以看到VideoView 其繼承是SurfaceView 和實現了MediaPlayerControl, SubtitleController.Anchor 接口
實現 MediaPlayerControl 接口主要是將 VideoView class this 指針傳遞給,所以 MediaController 中的事件監聽,比如上下片源切換,快進快退就可以通過MediaPlayerControl 接口類實現回調到 VideoView 中,這樣子就操作到具體對應的MediaPlayer 方法
base/core/java/android/widget/MediaController.java
public interface MediaPlayerControl {
void start();
void pause();
int getDuration();
int getCurrentPosition();
void seekTo(int pos);
boolean isPlaying();
int getBufferPercentage();
boolean canPause();
boolean canSeekBackward();
boolean canSeekForward();
/**
* Get the audio session id for the player used by this VideoView. This can be used to
* apply audio effects to the audio track of a video.
* @return The audio session, or 0 if there was an error.
*/
int getAudioSessionId();
}