MediaController簡(jiǎn)介
官方API 文檔
MediaController | Android Developers
使用demo
Android自帶的MediaController實(shí)現(xiàn)網(wǎng)絡(luò)播放和本地播放
結(jié)合VideoView和MediaController的例子簡(jiǎn)單介紹下
base/core/java/android/widget/VideoView.java
public class VideoView extends SurfaceView
implements MediaPlayerControl, SubtitleController.Anchor {
// ....
// MediaPlayerControl 接口類方法實(shí)現(xiàn)
@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 和實(shí)現(xiàn)了MediaPlayerControl, SubtitleController.Anchor 接口
實(shí)現(xiàn) MediaPlayerControl 接口主要是將 VideoView class this 指針傳遞給,所以 MediaController 中的事件監(jiān)聽(tīng),比如上下片源切換丐重,快進(jìn)快退就可以通過(guò)MediaPlayerControl 接口類實(shí)現(xiàn)回調(diào)到 VideoView 中腔召,這樣子就操作到具體對(duì)應(yīng)的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();
}