package com.ltnc.tempvideoview;
import java.io.IOException;
import java.util.Map;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.net.Uri;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.View;
import android.view.View.MeasureSpec;
import android.widget.ImageView;
import android.widget.MediaController;
import android.widget.MediaController.MediaPlayerControl;
public class MyAudiView extends ImageView implements MediaPlayerControl {
private String TAG = "VideoView";
// settable by the client
private Uri mUri;
private Map<string, string=""> mHeaders;
private int mDuration;
// all possible internal states
private static final int STATE_ERROR = -1;
private static final int STATE_IDLE = 0;
private static final int STATE_PREPARING = 1;
private static final int STATE_PREPARED = 2;
private static final int STATE_PLAYING = 3;
private static final int STATE_PAUSED = 4;
private static final int STATE_PLAYBACK_COMPLETED = 5;
private static final int STATE_SUSPEND = 6;
private static final int STATE_RESUME = 7;
private static final int STATE_SUSPEND_UNSUPPORTED = 8;
// mCurrentState is a VideoView object's current state.
// mTargetState is the state that a method caller intends to reach.
// For instance, regardless the VideoView object's current state,
// calling pause() intends to bring the object to a target state
// of STATE_PAUSED.
private int mCurrentState = STATE_IDLE;
private int mTargetState = STATE_IDLE;
// All the stuff we need for playing and showing a video
private SurfaceHolder mSurfaceHolder = null;
private MediaPlayer mMediaPlayer = null;
private int mVideoWidth;
private int mVideoHeight;
private int mSurfaceWidth;
private int mSurfaceHeight;
private MediaController mMediaController;
private OnCompletionListener mOnCompletionListener;
private MediaPlayer.OnPreparedListener mOnPreparedListener;
private int mCurrentBufferPercentage;
private OnErrorListener mOnErrorListener;
private int mSeekWhenPrepared; // recording the seek position while preparing
private boolean mCanPause;
private boolean mCanSeekBack;
private boolean mCanSeekForward;
private int mStateWhenSuspended; //state before calling suspend()
private Context mContext;
public MyAudiView(Context context) {
super(context);
= context;
();
}
public MyAudiView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
= context;
();
}
public MyAudiView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
= context;
();
}
private void initVideoView() {
i(TAG, "initVideoView");
= STATE_IDLE;
= STATE_IDLE;
}
public void setVideoPath(String path) {
i(TAG, "setVideoPath");
(Uri.parse(path));
}
public void setVideoURI(Uri uri) {
i(TAG, "setVideoURI");
= uri;
= 0;
();
();
();
}
public void stopPlayback() {
i(TAG, "stopPlayback");
if (mMediaPlayer != null) {
stop();
release();
= null;
= STATE_IDLE;
= STATE_IDLE;
}
}
private void openVideo() {
i(TAG, "openVideo");
if (mUri == null) {
// not ready for playback just yet, will try again later
return;
}
// Tell the music playback service to pause
// TODO: these constants need to be published somewhere in the
// framework.
= new Intent("com.android.music.musicservicecommand");
putExtra("command", "pause");
sendBroadcast(i);
// we shouldn't clear the target state, because somebody might have
// called start() previously
(false);
try {
= new MediaPlayer();
setOnPreparedListener(mPreparedListener);
= -1;
setOnCompletionListener(mCompletionListener);
setOnErrorListener(mErrorListener);
setOnBufferingUpdateListener(mBufferingUpdateListener);
= 0;
setDataSource(mContext, mUri);
// mMediaPlayer.setDisplay(mSurfaceHolder);
setAudioStreamType(AudioManager.STREAM_MUSIC);
setScreenOnWhilePlaying(true);
prepareAsync();
// we don't set the target state here either, but preserve the
// target state that was there before.
= STATE_PREPARING;
();
} catch (IOException ex) {
w(TAG, "Unable to open content: " + mUri, ex);
= STATE_ERROR;
= STATE_ERROR;
onError(mMediaPlayer,
MEDIA_ERROR_UNKNOWN, 0);
return;
} catch (IllegalArgumentException ex) {
w(TAG, "Unable to open content: " + mUri, ex);
= STATE_ERROR;
= STATE_ERROR;
onError(mMediaPlayer,
MEDIA_ERROR_UNKNOWN, 0);
return;
}
}
public void setMediaController(MediaController controller) {
i(TAG, "setMediaController");
if (mMediaController != null) {
hide();
}
= controller;
();
}
private void attachMediaController() {
i(TAG, "attachMediaController");
if (mMediaPlayer != null && mMediaController != null) {
setMediaPlayer(this);
View anchorView = this.getParent() instanceof View ? (View) this
getParent() : this;
setAnchorView(anchorView);
setEnabled(isInPlaybackState());
}
}
OnPreparedListener mPreparedListener = new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
i(TAG, "onPrepared");
= STATE_PREPARED;
// Get the capabilities of the player for this stream
// Metadata data = mp.getMetadata(MediaPlayer.METADATA_ALL,
// MediaPlayer.BYPASS_METADATA_FILTER);
//
// if (data != null) {
// mCanPause = !data.has(Metadata.PAUSE_AVAILABLE)
// || data.getBoolean(Metadata.PAUSE_AVAILABLE);
// mCanSeekBack = !data.has(Metadata.SEEK_BACKWARD_AVAILABLE)
// || data.getBoolean(Metadata.SEEK_BACKWARD_AVAILABLE);
// mCanSeekForward = !data.has(Metadata.SEEK_FORWARD_AVAILABLE)
// || data.getBoolean(Metadata.SEEK_FORWARD_AVAILABLE);
// } else {
= mCanSeekBack = mCanSeekForward = true;
// }
if (mOnPreparedListener != null) {
onPrepared(mMediaPlayer);
}
if (mMediaController != null) {
setEnabled(true);
}
// mVideoWidth = mp.getVideoWidth();
// mVideoHeight = mp.getVideoHeight();
int seekToPosition = mSeekWhenPrepared; // mSeekWhenPrepared may be
// changed after seekTo()
// call
if (seekToPosition != 0) {
(seekToPosition);
}
// if (mVideoWidth != 0 && mVideoHeight != 0) {
// //Log.i("@@@@", "video size: " + mVideoWidth +"/"+ mVideoHeight);
// getHolder().setFixedSize(mVideoWidth, mVideoHeight);
// if (mSurfaceWidth == mVideoWidth && mSurfaceHeight ==
// mVideoHeight) {
// // We didn't actually change the size (it was already at the size
// // we need), so we won't get a "surface changed" callback, so
// // start the video here instead of in the callback.
if (mTargetState == STATE_PLAYING) {
();
if (mMediaController != null) {
show();
}
} else if (!isPlaying()
&& (seekToPosition != 0 || getCurrentPosition() > 0)) {
if (mMediaController != null) {
// Show the media controls when we're paused into a video
// and make 'em stick.
show(0);
}
}
// }
// } else {
// // We don't know the video size yet, but should start anyway.
// // The video size might be reported to us later.
// if (mTargetState == STATE_PLAYING) {
// start();
// }
// }
}
};
private MediaPlayer.OnCompletionListener mCompletionListener = new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
i(TAG, "onCompletion");
= STATE_PLAYBACK_COMPLETED;
= STATE_PLAYBACK_COMPLETED;
if (mMediaController != null) {
hide();
}
if (mOnCompletionListener != null) {
onCompletion(mMediaPlayer);
}
}
};
private MediaPlayer.OnErrorListener mErrorListener = new MediaPlayer.OnErrorListener() {
public boolean onError(MediaPlayer mp, int framework_err, int impl_err) {
i(TAG, "onError");
d(TAG, "Error: " + framework_err + "," + impl_err);
= STATE_ERROR;
= STATE_ERROR;
if (mMediaController != null) {
hide();
}
/* If an error handler has been supplied, use it and finish. */
if (mOnErrorListener != null) {
if (mOnErrorListener.onError(mMediaPlayer, framework_err,
)) {
return true;
}
}
/*
* Otherwise, pop up an error dialog so the user knows that
* something bad has happened. Only try and pop up the dialog if
* we're attached to a window. When we're going away and no longer
* have a window, don't bother showing the user an error.
*/
if (getWindowToken() != null) {
= mContext.getResources();
int messageId;
if (framework_err == MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK) {
= 123;
} else {
= 456;
}
new AlertDialog.Builder(mContext)
setTitle("error")
setMessage(messageId)
setPositiveButton("error",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
/*
* If we get here, there is no onError
* listener, so at least inform them
* that the video is over.
*/
if (mOnCompletionListener != null) {
mOnCompletionListener
onCompletion(mMediaPlayer);
}
}
}).setCancelable(false).show();
}
return true;
}
};
private MediaPlayer.OnBufferingUpdateListener mBufferingUpdateListener = new MediaPlayer.OnBufferingUpdateListener() {
public void onBufferingUpdate(MediaPlayer mp, int percent) {
i(TAG, "onBufferingUpdate");
= percent;
}
};
/**
* Register a callback to be invoked when the media file is loaded and ready
* to go.
*
* @param l
* The callback that will be run
*/
public void setOnPreparedListener(MediaPlayer.OnPreparedListener l) {
i(TAG, "setOnPreparedListener");
= l;
}
/**
* Register a callback to be invoked when the end of a media file has been
* reached during playback.
*
* @param l
* The callback that will be run
*/
public void setOnCompletionListener(OnCompletionListener l) {
i(TAG, "setOnCompletionListener");
= l;
}
/**
* Register a callback to be invoked when an error occurs during playback or
* setup. If no listener is specified, or if the listener returned false,
* VideoView will inform the user of any errors.
*
* @param l
* The callback that will be run
*/
public void setOnErrorListener(OnErrorListener l) {
i(TAG, "setOnErrorListener");
= l;
}
/*
* SurfaceHolder.Callback mSHCallback = new SurfaceHolder.Callback() {
* public void surfaceChanged(SurfaceHolder holder, int format, int w, int
* h) { Log.i(TAG, "surfaceChanged"); mSurfaceWidth = w; mSurfaceHeight = h;
* boolean isValidState = (mTargetState == STATE_PLAYING); boolean
* hasValidSize = (mVideoWidth == w && mVideoHeight == h); if (mMediaPlayer
* != null && isValidState && hasValidSize) { if (mSeekWhenPrepared != 0) {
* seekTo(mSeekWhenPrepared); } start(); if (mMediaController != null) {
* mMediaController.show(); } } }
*
* public void surfaceCreated(SurfaceHolder holder) { Log.i(TAG,
* "surfaceCreated"); mSurfaceHolder = holder; //resume() was called before
* surfaceCreated() // if (mMediaPlayer != null && mCurrentState ==
* STATE_SUSPEND // && mTargetState == STATE_RESUME) { //
* mMediaPlayer.setDisplay(mSurfaceHolder); // resume(); // } else {
* openVideo(); // } }
*
* public void surfaceDestroyed(SurfaceHolder holder) { Log.i(TAG,
* "surfaceDestroyed"); // after we return from this we can't use the
* surface any more mSurfaceHolder = null; if (mMediaController != null)
* mMediaController.hide(); if (mCurrentState != STATE_SUSPEND) {
* release(true); } } };
*/
/*
* release the media player in any state
*/
private void release(boolean cleartargetstate) {
i(TAG, "release");
if (mMediaPlayer != null) {
reset();
release();
= null;
= STATE_IDLE;
if (cleartargetstate) {
= STATE_IDLE;
}
}
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
i(TAG, "onTouchEvent");
if (isInPlaybackState() && mMediaController != null) {
();
}
return false;
}
@Override
public boolean onTrackballEvent(MotionEvent ev) {
i(TAG, "onTrackballEvent");
if (isInPlaybackState() && mMediaController != null) {
();
}
return false;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
i(TAG, "onKeyDown");
boolean isKeyCodeSupported = keyCode != KeyEvent.KEYCODE_BACK
&& keyCode != KeyEvent.KEYCODE_VOLUME_UP
&& keyCode != KeyEvent.KEYCODE_VOLUME_DOWN
&& keyCode != KeyEvent.KEYCODE_MENU
&& keyCode != KeyEvent.KEYCODE_CALL
&& keyCode != KeyEvent.KEYCODE_ENDCALL;
if (isInPlaybackState() &&
&& mMediaController != null) {
if (keyCode == KeyEvent.KEYCODE_HEADSETHOOK
|| keyCode == KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE) {
if (mMediaPlayer.isPlaying()) {
();
show();
} else {
();
hide();
}
return true;
} else if (keyCode == KeyEvent.KEYCODE_MEDIA_STOP
&& mMediaPlayer.isPlaying()) {
();
show();
} else {
();
}
}
return super.onKeyDown(keyCode, event);
}
private void toggleMediaControlsVisiblity() {
i(TAG, "toggleMediaControlsVisiblity");
if (mMediaController.isShowing()) {
hide();
} else {
show();
}
}
public void start() {
i(TAG, "start");
if (isInPlaybackState()) {
start();
= STATE_PLAYING;
}
= STATE_PLAYING;
}
public void pause() {
i(TAG, "pause");
if (isInPlaybackState()) {
if (mMediaPlayer.isPlaying()) {
pause();
= STATE_PAUSED;
}
}
= STATE_PAUSED;
}
// cache duration as mDuration for faster access
public int getDuration() {
i(TAG, "getDuration");
if (isInPlaybackState()) {
if (mDuration > 0) {
return mDuration;
}
= mMediaPlayer.getDuration();
return mDuration;
}
= -1;
return mDuration;
}
public int getCurrentPosition() {
i(TAG, "getCurrentPosition");
if (isInPlaybackState()) {
return mMediaPlayer.getCurrentPosition();
}
return 0;
}
public void seekTo(int msec) {
i(TAG, "seekTo");
if (isInPlaybackState()) {
seekTo(msec);
= 0;
} else {
= msec;
}
}
public boolean isPlaying() {
// Log.i(TAG, "isPlaying");
return isInPlaybackState() && mMediaPlayer.isPlaying();
}
public int getBufferPercentage() {
i(TAG, "getBufferPercentage");
if (mMediaPlayer != null) {
return mCurrentBufferPercentage;
}
return 0;
}
private boolean isInPlaybackState() {
// Log.i(TAG, "isInPlaybackState");
return (mMediaPlayer != null && mCurrentState !=
&& mCurrentState != STATE_IDLE && mCurrentState != STATE_PREPARING);
}
public boolean canPause() {
i(TAG, "canPause");
return mCanPause;
}
public boolean canSeekBackward() {
i(TAG, "canSeekBackward");
return mCanSeekBack;
}
public boolean canSeekForward() {
i(TAG, "canSeekForward");
return mCanSeekForward;
}
}
</string,>