Android Tutorial - Media : Video

Record video

  

package app.test;

import java.io.File;
import java.io.IOException;
import android.app.Activity;
import android.hardware.Camera;
import android.media.MediaRecorder;
import android.media.MediaRecorder.OnErrorListener;
import android.media.MediaRecorder.OnInfoListener;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.View;
import android.widget.Button;
import android.widget.MediaController;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

public class Test extends Activity implements
        SurfaceHolder.Callback, OnInfoListener, OnErrorListener {

  private static final String TAG = "RecordVideo";
  private MediaRecorder mRecorder = null;
  private String mOutputFileName;
  private VideoView mVideoView = null;
  private SurfaceHolder mHolder = null;
  private Button mInitBtn = null;
  private Button mStartBtn = null;
  private Button mStopBtn = null;
  private Button mPlayBtn = null;
  private Button mStopPlayBtn = null;
  private Camera mCamera = null;
  private TextView mRecordingMsg = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.v(TAG, "in onCreate");
        setContentView(R.layout.main);

        mInitBtn = (Button) findViewById(R.id.initBtn);
        mStartBtn = (Button) findViewById(R.id.beginBtn);
        mStopBtn = (Button) findViewById(R.id.stopBtn);
        mPlayBtn = (Button) findViewById(R.id.playRecordingBtn);
        mStopPlayBtn = (Button) findViewById(R.id.stopPlayingRecordingBtn);
        mRecordingMsg = (TextView) findViewById(R.id.recording);

        mVideoView = (VideoView)this.findViewById(R.id.videoView);
    }

    private boolean initCamera() {
        try {
            mCamera  = Camera.open();
            Camera.Parameters camParams = mCamera.getParameters();
            mCamera.lock();
            mCamera.setDisplayOrientation(90);
            mCamera.setParameters(camParams);
            mHolder = mVideoView.getHolder();
            mHolder.addCallback(this);
            mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        }
        catch(RuntimeException re) {
          re.printStackTrace();
          return false;
        }
        return true;
    }
    private void releaseRecorder() {
      if(mRecorder != null) {
        mRecorder.release();
        mRecorder = null;
      }
    }
    private void releaseCamera() {
      if(mCamera != null) {
        try {
        mCamera.reconnect();
      } catch (IOException e) {
        e.printStackTrace();
      }
        mCamera.release();
        mCamera = null;
      }
    }
    @Override
    protected void onResume() {
      super.onResume();
        mInitBtn.setEnabled(false);
        mStartBtn.setEnabled(false);
        mStopBtn.setEnabled(false);
        mPlayBtn.setEnabled(false);
        mStopPlayBtn.setEnabled(false);
      if(!initCamera())
        finish();
    }
    @Override
    protected void onPause() {
        Log.v(TAG, "in onPause");
      super.onPause();
      releaseRecorder();
      releaseCamera();
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
    public void doClick(View view) {
      switch(view.getId()) {
      case R.id.initBtn:
            initRecorder();
            break;
      case R.id.beginBtn:
            beginRecording();
            break;
      case R.id.stopBtn:
            stopRecording();
            break;
      case R.id.playRecordingBtn:
            playRecording();
            break;
      case R.id.stopPlayingRecordingBtn:
            stopPlayingRecording();
            break;
      }
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        try {
        mCamera.setPreviewDisplay(mHolder);
          mCamera.startPreview();
        } catch (IOException e) {
      e.printStackTrace();
    }
        mInitBtn.setEnabled(true);
    }
    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
    }

  @Override
  public void surfaceChanged(SurfaceHolder holder, int format, int width,
      int height) {
  }

    private void initRecorder() {
        if(mRecorder != null) return;

        mOutputFileName = Environment.getExternalStorageDirectory() +
                               "/videooutput.mp4";

        File outFile = new File(mOutputFileName);
        if(outFile.exists()) {
            outFile.delete();
        }

        try {
          mCamera.stopPreview();
          mCamera.unlock();
            mRecorder = new MediaRecorder();
            mRecorder.setCamera(mCamera);

            mRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
            mRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
            mRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
            mRecorder.setVideoSize(176, 144);
            mRecorder.setVideoFrameRate(15);
            mRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.MPEG_4_SP);
            mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
            mRecorder.setMaxDuration(7000); // limit to 7 seconds
            mRecorder.setPreviewDisplay(mHolder.getSurface());
            mRecorder.setOutputFile(mOutputFileName);

            mRecorder.prepare();
            Log.v(TAG, "MediaRecorder initialized");
            mInitBtn.setEnabled(false);
            mStartBtn.setEnabled(true);
        }
        catch(Exception e) {
            Log.v(TAG, "MediaRecorder failed to initialize");
            e.printStackTrace();

        }
    }

    private void beginRecording() {
      mRecorder.setOnInfoListener(this);
      mRecorder.setOnErrorListener(this);
        mRecorder.start();
        mRecordingMsg.setText("RECORDING");
        mStartBtn.setEnabled(false);
        mStopBtn.setEnabled(true);
    }

    private void stopRecording() {
        if (mRecorder != null) {
          mRecorder.setOnErrorListener(null);
          mRecorder.setOnInfoListener(null);
          try {
                mRecorder.stop();
          }
          catch(IllegalStateException e) {
          }
          releaseRecorder();
            mRecordingMsg.setText("");
            releaseCamera();
            mStartBtn.setEnabled(false);
            mStopBtn.setEnabled(false);
            mPlayBtn.setEnabled(true);
        }
    }

  private void playRecording() {
        MediaController mc = new MediaController(this);
        mVideoView.setMediaController(mc);
        mVideoView.setVideoPath(mOutputFileName);
        mVideoView.start();
        mStopPlayBtn.setEnabled(true);
    }

    private void stopPlayingRecording() {
      mVideoView.stopPlayback();
    }

  @Override
  public void onInfo(MediaRecorder mr, int what, int extra) {
    if(what == MediaRecorder.MEDIA_RECORDER_INFO_MAX_DURATION_REACHED) {
      stopRecording();
      Toast.makeText(this, "Recording limit has been reached. Stopping the recording",
          Toast.LENGTH_SHORT).show();
    }
  }

  @Override
  public void onError(MediaRecorder mr, int what, int extra) {
    stopRecording();
    Toast.makeText(this, "Recording error has occurred. Stopping the recording",
        Toast.LENGTH_SHORT).show();
  }
}

//main.xml

<?xml version="1.0" encoding="utf-8"?>
<!-- This file is /res/layout/main.xml -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical" android:layout_width="fill_parent"
  android:layout_height="fill_parent">

  <Button android:id="@+id/beginBtn" android:layout_width="fill_parent"
    android:layout_height="wrap_content" android:text="Begin Recording"
    android:onClick="doClick"  android:enabled="false" />

  <Button android:id="@+id/stopBtn" android:layout_width="fill_parent"
    android:layout_height="wrap_content" android:text="Stop Recording"
    android:onClick="doClick" />

  <Button android:id="@+id/playRecordingBtn" android:layout_width="fill_parent"
    android:layout_height="wrap_content" android:text="Play Recording"
    android:onClick="doClick" />

  <Button android:id="@+id/stopPlayingRecordingBtn"
    android:layout_width="fill_parent" android:layout_height="wrap_content"
    android:text="Stop Playing Recording"
    android:onClick="doClick" />

    <RelativeLayout android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:gravity="center">
        
      <VideoView android:id="@+id/videoView" android:layout_width="150dip"
        android:layout_height="100dip" />
        
    </RelativeLayout> 

</LinearLayout>

Capture Video

  

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">
  <Button
    android:id="@+id/capture"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Take a Video"
  />
  <TextView
    android:id="@+id/file"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
  />
</LinearLayout>
package app.test;

import java.io.File;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MyActivity extends Activity {
    
    private static final int REQUEST_VIDEO = 100;
    
    Button captureButton;
    TextView text;
    File destination;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        captureButton = (Button)findViewById(R.id.capture);
        captureButton.setOnClickListener(listener);
        
        text = (TextView)findViewById(R.id.file);
        
        destination = new File(Environment.getExternalStorageDirectory(),"myVideo");
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode == REQUEST_VIDEO && resultCode == Activity.RESULT_OK) {
            String location = data.getData().toString();
            text.setText(location);
        }
    }
    
    private View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(destination));
            intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0);
            startActivityForResult(intent, REQUEST_VIDEO);
        }
    };
} 

Store image and video

  

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">
  <Button
    android:id="@+id/imageButton"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="Images"
  />
  <Button
    android:id="@+id/videoButton"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="Video"
  />
  <Button
    android:id="@+id/audioButton"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="Audio"
  />
</LinearLayout>
package app.test;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class Test extends Activity implements View.OnClickListener {

    private static final int REQUEST_CAPTURE = 100;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        Button images = (Button)findViewById(R.id.imageButton);
        images.setOnClickListener(this);
        Button videos = (Button)findViewById(R.id.videoButton);
        videos.setOnClickListener(this);
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode == REQUEST_CAPTURE && resultCode == Activity.RESULT_OK) {
            Toast.makeText(this, "All Done!", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onClick(View v) {
        ContentValues values;
        Intent intent;
        Uri storeLocation;
        
        switch(v.getId()) {
        case R.id.imageButton:
            values = new ContentValues(2);
            values.put(MediaStore.Images.ImageColumns.DATE_TAKEN, System.currentTimeMillis());
            values.put(MediaStore.Images.ImageColumns.DESCRIPTION, "Sample Image");
            storeLocation = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, storeLocation);
            startActivityForResult(intent, REQUEST_CAPTURE);
            return;
        case R.id.videoButton:
            values = new ContentValues(2);
            values.put(MediaStore.Video.VideoColumns.ARTIST, "Artist");
            values.put(MediaStore.Video.VideoColumns.DESCRIPTION, "Sample Video Clip");
            storeLocation = getContentResolver().insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, values);
            intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, storeLocation);
            startActivityForResult(intent, REQUEST_CAPTURE);
            return;
        default:
            return;
        }
    } 

}

Load video file from local file system

  

package app.test;

import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.widget.MediaController;
import android.widget.VideoView;

public class MainActivity extends Activity {
    /** Called when the activity is first created. */
  @Override
  protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      this.setContentView(R.layout.main);

      VideoView videoView = (VideoView)this.findViewById(R.id.videoView);
      MediaController mc = new MediaController(this);
      videoView.setMediaController(mc);

        videoView.setVideoPath(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES) +"/movie.mp4");

 
      videoView.requestFocus();
      videoView.start();
  }
}

//main.xml

<?xml version="1.0" encoding="utf-8"?>
<!-- This file is /res/layout/main.xml -->
<LinearLayout
 android:layout_width="fill_parent" android:layout_height="fill_parent"
 xmlns:android="http://schemas.android.com/apk/res/android">
   <VideoView  android:id="@+id/videoView"
      android:layout_width="190px"  android:layout_height="wrap_content"
    /> 

</LinearLayout>

Uri for local video file

  


package app.test;

import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.widget.MediaController;
import android.widget.VideoView;

public class MainActivity extends Activity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      this.setContentView(R.layout.main);

      VideoView videoView = (VideoView)this.findViewById(R.id.videoView);
      MediaController mc = new MediaController(this);
      videoView.setMediaController(mc);

      videoView.setVideoURI(Uri.parse("file://" +Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES) +"/movie.mp4"));
 
      videoView.requestFocus();
      videoView.start();
  }
}


//main.xml

<?xml version="1.0" encoding="utf-8"?>
<!-- This file is /res/layout/main.xml -->
<LinearLayout
 android:layout_width="fill_parent" android:layout_height="fill_parent"
 xmlns:android="http://schemas.android.com/apk/res/android">
   <VideoView  android:id="@+id/videoView"
      android:layout_width="190px"  android:layout_height="wrap_content"
    /> 

</LinearLayout>

Custom Video Player

  
package app.test;

import java.io.IOException;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Display;
import android.widget.LinearLayout;

import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnInfoListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.media.MediaPlayer.OnSeekCompleteListener;
import android.media.MediaPlayer.OnVideoSizeChangedListener;

import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class Test extends Activity implements
    OnCompletionListener, OnErrorListener, OnInfoListener,
    OnPreparedListener, OnSeekCompleteListener, OnVideoSizeChangedListener,
    SurfaceHolder.Callback {
  Display currentDisplay;

  SurfaceView surfaceView;
  SurfaceHolder surfaceHolder;

  MediaPlayer mediaPlayer;

  int videoWidth = 0,videoHeight = 0;

  boolean readyToPlay = false;

  public final static String LOGTAG = "CUSTOM_VIDEO_PLAYER";

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    surfaceView = (SurfaceView) this.findViewById(R.id.SurfaceView);
    surfaceHolder = surfaceView.getHolder();
    surfaceHolder.addCallback(this);
    surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

    mediaPlayer = new MediaPlayer();
    mediaPlayer.setOnCompletionListener(this);
    mediaPlayer.setOnErrorListener(this);
    mediaPlayer.setOnInfoListener(this);
    mediaPlayer.setOnPreparedListener(this);
    mediaPlayer.setOnSeekCompleteListener(this);
    mediaPlayer.setOnVideoSizeChangedListener(this);
    String filePath = Environment.getExternalStorageDirectory().getPath()
        + "/Test.m4v";

    try {
      mediaPlayer.setDataSource(filePath);
    } catch (Exception e) {
      Log.v(LOGTAG, e.getMessage());
      finish();
    }
    currentDisplay = getWindowManager().getDefaultDisplay();
  }

  public void surfaceCreated(SurfaceHolder holder) {
    mediaPlayer.setDisplay(holder);

    try {
      mediaPlayer.prepare();
    } catch (Exception e) {
      finish();
    }
  }

  public void surfaceChanged(SurfaceHolder holder, int format, int width,
      int height) {
  }

  public void surfaceDestroyed(SurfaceHolder holder) {
  }

  public void onCompletion(MediaPlayer mp) {
    finish();
  }

  public boolean onError(MediaPlayer mp, int whatError, int extra) {
    Log.v(LOGTAG, "onError Called");

    if (whatError == MediaPlayer.MEDIA_ERROR_SERVER_DIED) {
      Log.v(LOGTAG, "Media Error, Server Died " + extra);
    } else if (whatError == MediaPlayer.MEDIA_ERROR_UNKNOWN) {
      Log.v(LOGTAG, "Media Error, Error Unknown " + extra);
    }

    return false;
  }

  public boolean onInfo(MediaPlayer mp, int whatInfo, int extra) {
    if (whatInfo == MediaPlayer.MEDIA_INFO_BAD_INTERLEAVING) {
      Log.v(LOGTAG, "Media Info, Media Info Bad Interleaving " + extra);
    } else if (whatInfo == MediaPlayer.MEDIA_INFO_NOT_SEEKABLE) {
      Log.v(LOGTAG, "Media Info, Media Info Not Seekable " + extra);
    } else if (whatInfo == MediaPlayer.MEDIA_INFO_UNKNOWN) {
      Log.v(LOGTAG, "Media Info, Media Info Unknown " + extra);
    } else if (whatInfo == MediaPlayer.MEDIA_INFO_VIDEO_TRACK_LAGGING) {
      Log.v(LOGTAG, "MediaInfo, Media Info Video Track Lagging " + extra);
    }else if (whatInfo == MediaPlayer.MEDIA_INFO_METADATA_UPDATE) {
        Log.v(LOGTAG,"MediaInfo, Media Info Metadata Update " + extra);
    }
    return false;
  }

  public void onPrepared(MediaPlayer mp) {
    videoWidth = mp.getVideoWidth();
    videoHeight = mp.getVideoHeight();
    surfaceView.setLayoutParams(new LinearLayout.LayoutParams(videoWidth,
        videoHeight));
    mp.start();
  }

  public void onSeekComplete(MediaPlayer mp) {
  }

  public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
  }
}
//main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
  android:id="@+id/MainView"
    >
<SurfaceView android:id="@+id/SurfaceView" android:layout_height="wrap_content" android:layout_width="wrap_content"></SurfaceView>
</LinearLayout> 

Get Video size

  

package app.test;

import java.io.IOException;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Display;
import android.widget.LinearLayout;

import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnInfoListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.media.MediaPlayer.OnSeekCompleteListener;
import android.media.MediaPlayer.OnVideoSizeChangedListener;

import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import android.widget.MediaController;

public class Test extends Activity implements
    OnCompletionListener, OnErrorListener, OnInfoListener,
    OnPreparedListener, OnSeekCompleteListener, OnVideoSizeChangedListener,
    SurfaceHolder.Callback, MediaController.MediaPlayerControl {
  Display currentDisplay;

  SurfaceView surfaceView;
  SurfaceHolder surfaceHolder;

  MediaPlayer mediaPlayer;
    MediaController controller;

  int videoWidth = 0, videoHeight = 0;

  boolean readyToPlay = false;

  public final static String LOGTAG = "CUSTOM_VIDEO_PLAYER";

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    surfaceView = (SurfaceView) this.findViewById(R.id.SurfaceView);
    surfaceHolder = surfaceView.getHolder();
    surfaceHolder.addCallback(this);
    surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

    mediaPlayer = new MediaPlayer();
    mediaPlayer.setOnCompletionListener(this);
    mediaPlayer.setOnErrorListener(this);
    mediaPlayer.setOnInfoListener(this);
    mediaPlayer.setOnPreparedListener(this);
    mediaPlayer.setOnSeekCompleteListener(this);
    mediaPlayer.setOnVideoSizeChangedListener(this);

    String filePath = Environment.getExternalStorageDirectory().getPath()
        + "/Test.m4v";

    try {
      mediaPlayer.setDataSource(filePath);
    } catch (Exception e) {
      finish();
    }
      controller = new MediaController(this);
    currentDisplay = getWindowManager().getDefaultDisplay();
  }
  public void surfaceCreated(SurfaceHolder holder) {
    mediaPlayer.setDisplay(holder);
    try {
      mediaPlayer.prepare();
    } catch (Exception e) {
      finish();
    }
  }
  public void surfaceChanged(SurfaceHolder holder, int format, int width,
      int height) {
  }
  public void surfaceDestroyed(SurfaceHolder holder) {
  }
  public void onCompletion(MediaPlayer mp) {
    finish();
  }
  public boolean onError(MediaPlayer mp, int whatError, int extra) {
    if (whatError == MediaPlayer.MEDIA_ERROR_SERVER_DIED) {
      Log.v(LOGTAG, "Media Error, Server Died " + extra);
    } else if (whatError == MediaPlayer.MEDIA_ERROR_UNKNOWN) {
      Log.v(LOGTAG, "Media Error, Error Unknown " + extra);
    }

    return false;
  }

  public boolean onInfo(MediaPlayer mp, int whatInfo, int extra) {
    if (whatInfo == MediaPlayer.MEDIA_INFO_BAD_INTERLEAVING) {
      Log.v(LOGTAG, "Media Info, Media Info Bad Interleaving " + extra);
    } else if (whatInfo == MediaPlayer.MEDIA_INFO_NOT_SEEKABLE) {
      Log.v(LOGTAG, "Media Info, Media Info Not Seekable " + extra);
    } else if (whatInfo == MediaPlayer.MEDIA_INFO_UNKNOWN) {
      Log.v(LOGTAG, "Media Info, Media Info Unknown " + extra);
    } else if (whatInfo == MediaPlayer.MEDIA_INFO_VIDEO_TRACK_LAGGING) {
      Log.v(LOGTAG, "MediaInfo, Media Info Video Track Lagging " + extra);
      } else if (whatInfo == MediaPlayer.MEDIA_INFO_METADATA_UPDATE) {
        Log.v(LOGTAG,"MediaInfo, Media Info Metadata Update " + extra);
    }
    return false;
  }

  public void onPrepared(MediaPlayer mp) {
    videoWidth = mp.getVideoWidth();
    videoHeight = mp.getVideoHeight();
    if (videoWidth > currentDisplay.getWidth()
        || videoHeight > currentDisplay.getHeight()) {
      float heightRatio = (float) videoHeight
          / (float) currentDisplay.getHeight();
      float widthRatio = (float) videoWidth
          / (float) currentDisplay.getWidth();

      if (heightRatio > 1 || widthRatio > 1) {
        if (heightRatio > widthRatio) {
          videoHeight = (int) Math.ceil((float) videoHeight
              / (float) heightRatio);
          videoWidth = (int) Math.ceil((float) videoWidth
              / (float) heightRatio);
        } else {
          videoHeight = (int) Math.ceil((float) videoHeight
              / (float) widthRatio);
          videoWidth = (int) Math.ceil((float) videoWidth
              / (float) widthRatio);
        }
      }
    }

    surfaceView.setLayoutParams(new LinearLayout.LayoutParams(videoWidth,
        videoHeight));
    mp.start();
    
    controller.setMediaPlayer(this);
      controller.setAnchorView(this.findViewById(R.id.MainView));
      controller.setEnabled(true);
      controller.show();    
  }
  public void onSeekComplete(MediaPlayer mp) {
  }

  public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
  }
  
  public boolean canPause() {
     return true;
  }

    public boolean canSeekBackward() {
        return true;
    }

    public boolean canSeekForward() {
        return true;
    }

    public int getBufferPercentage() {
        return 0;
    }

    public int getCurrentPosition() {
        return mediaPlayer.getCurrentPosition();
    }

    public int getDuration() {
        return mediaPlayer.getDuration();
    }

    public boolean isPlaying() {
        return mediaPlayer.isPlaying();
    }

    public void pause() {
        if (mediaPlayer.isPlaying()) {
            mediaPlayer.pause();
        }
    }

    public void seekTo(int pos) {
        mediaPlayer.seekTo(pos);
    }

    public void start() {
        mediaPlayer.start();
    }  
    
    @Override
  public boolean onTouchEvent(MotionEvent ev) {
        if (controller.isShowing()) {
            controller.hide();
        } else {
            controller.show();
        }
        return false;
    }
    
}
//main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
  android:id="@+id/MainView"
    >
<SurfaceView android:id="@+id/SurfaceView" android:layout_height="wrap_content" android:layout_width="wrap_content"></SurfaceView> 

</LinearLayout>

Display video with VideoView

  


package app.test;

import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.widget.VideoView;

public class Test extends Activity {
  VideoView vv;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    vv = (VideoView) this.findViewById(R.id.VideoView);
    Uri videoUri = Uri.parse(Environment.getExternalStorageDirectory().getPath()+ "/Test.m4v");
    // Uri videoUri = Uri.parse(Environment.getExternalStorageDirectory().getPath() + "/Test.m4v");
    vv.setVideoURI(videoUri);
    vv.start();
  }
}
//main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<VideoView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/VideoView"></VideoView> 

</LinearLayout>

Using MediaController to control Video

  
package app.test;

import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.widget.MediaController;
import android.widget.VideoView;

public class Test extends Activity {
  VideoView vv;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    vv = (VideoView) this.findViewById(R.id.VideoView);
        Uri videoUri = Uri.parse(Environment.getExternalStorageDirectory().getPath()+ "/Test.m4v");
    // Uri videoUri = Uri.parse(Environment.getExternalStorageDirectory().getPath() + "/Test.m4v");

    vv.setVideoURI(videoUri);
    vv.setMediaController(new MediaController(this));
    vv.start();
  }
}
//main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<VideoView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/VideoView"></VideoView>
</LinearLayout> 

Play video from Youtube.com

  

package app.test;

import java.io.IOException;
import android.app.Activity;
import android.os.Bundle;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnInfoListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.media.MediaPlayer.OnSeekCompleteListener;
import android.media.MediaPlayer.OnVideoSizeChangedListener;
import android.util.Log;
import android.view.Display;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.MediaController;

public class Test extends Activity implements
    OnCompletionListener, OnErrorListener, OnInfoListener,
    OnBufferingUpdateListener, OnPreparedListener, OnSeekCompleteListener,
    OnVideoSizeChangedListener, SurfaceHolder.Callback,
    MediaController.MediaPlayerControl {

  MediaController controller;
  Display currentDisplay;
  SurfaceView surfaceView;
  SurfaceHolder surfaceHolder;
  MediaPlayer mediaPlayer;

  View mainView;
  TextView statusView;

  int videoWidth = 0,videoHeight = 0;

  boolean readyToPlay = false;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);
    mainView = this.findViewById(R.id.MainView);

    statusView = (TextView) this.findViewById(R.id.StatusTextView);

    surfaceView = (SurfaceView) this.findViewById(R.id.SurfaceView);
    surfaceHolder = surfaceView.getHolder();

    surfaceHolder.addCallback(this);
    surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

    mediaPlayer = new MediaPlayer();

    statusView.setText("MediaPlayer Created");

    mediaPlayer.setOnCompletionListener(this);
    mediaPlayer.setOnErrorListener(this);
    mediaPlayer.setOnInfoListener(this);
    mediaPlayer.setOnPreparedListener(this);
    mediaPlayer.setOnSeekCompleteListener(this);
    mediaPlayer.setOnVideoSizeChangedListener(this);
    mediaPlayer.setOnBufferingUpdateListener(this);

    String filePath = "rtsp://youtube.com/video.3gp";
    try {
      mediaPlayer.setDataSource(filePath);
    } catch (Exception e) {
      finish();
    }

    statusView.setText("MediaPlayer DataSource Set");
    currentDisplay = getWindowManager().getDefaultDisplay();
    controller = new MediaController(this);
  }

  public void surfaceCreated(SurfaceHolder holder) {
    mediaPlayer.setDisplay(holder);
    statusView.setText("MediaPlayer Display Surface Set");

    try {
      mediaPlayer.prepareAsync();
    } catch (Exception e) {
      finish();
    }

    statusView.setText("MediaPlayer Preparing");
  }

  public void surfaceChanged(SurfaceHolder holder, int format, int width,
      int height) {
  }
  public void surfaceDestroyed(SurfaceHolder holder) {
  }
  public void onCompletion(MediaPlayer mp) {
    statusView.setText("MediaPlayer Playback Completed");
  }

  public boolean onError(MediaPlayer mp, int whatError, int extra) {
    statusView.setText("MediaPlayer Error");
    if (whatError == MediaPlayer.MEDIA_ERROR_SERVER_DIED) {
      Log.v("", "Media Error, Server Died " + extra);
    } else if (whatError == MediaPlayer.MEDIA_ERROR_UNKNOWN) {
      Log.v("", "Media Error, Error Unknown " + extra);
    }
    return false;
  }

  public boolean onInfo(MediaPlayer mp, int whatInfo, int extra) {
    statusView.setText("MediaPlayer onInfo Called");
    if (whatInfo == MediaPlayer.MEDIA_INFO_BAD_INTERLEAVING) {
      Log.v("", "Media Info, Media Info Bad Interleaving " + extra);
    } else if (whatInfo == MediaPlayer.MEDIA_INFO_NOT_SEEKABLE) {
      Log.v("", "Media Info, Media Info Not Seekable " + extra);
    } else if (whatInfo == MediaPlayer.MEDIA_INFO_UNKNOWN) {
      Log.v("", "Media Info, Media Info Unknown " + extra);
    } else if (whatInfo == MediaPlayer.MEDIA_INFO_VIDEO_TRACK_LAGGING) {
      Log.v("", "MediaInfo, Media Info Video Track Lagging " + extra);
    } else if (whatInfo == MediaPlayer.MEDIA_INFO_METADATA_UPDATE) { 
      Log.v("","MediaInfo, Media Info Metadata Update " + extra); }
    return false;
  }

  public void onPrepared(MediaPlayer mp) {
    statusView.setText("MediaPlayer Prepared");
    videoWidth = mp.getVideoWidth();
    videoHeight = mp.getVideoHeight();
    if (videoWidth > currentDisplay.getWidth()
        || videoHeight > currentDisplay.getHeight()) {
      float heightRatio = (float) videoHeight
          / (float) currentDisplay.getHeight();
      float widthRatio = (float) videoWidth
          / (float) currentDisplay.getWidth();
      if (heightRatio > 1 || widthRatio > 1) {
        if (heightRatio > widthRatio) {
          videoHeight = (int) Math.ceil((float) videoHeight
              / (float) heightRatio);
          videoWidth = (int) Math.ceil((float) videoWidth
              / (float) heightRatio);
        } else {
          videoHeight = (int) Math.ceil((float) videoHeight
              / (float) widthRatio);
          videoWidth = (int) Math.ceil((float) videoWidth
              / (float) widthRatio);
        }
      }
    }

    surfaceView.setLayoutParams(new LinearLayout.LayoutParams(videoWidth,
        videoHeight));
    controller.setMediaPlayer(this);
    controller.setAnchorView(this.findViewById(R.id.MainView));
    controller.setEnabled(true);
    controller.show();

    mp.start();
    statusView.setText("MediaPlayer Started");
  }

  public void onSeekComplete(MediaPlayer mp) {
  }

  public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
    videoWidth = mp.getVideoWidth();
    videoHeight = mp.getVideoHeight();
    if (videoWidth > currentDisplay.getWidth()
        || videoHeight > currentDisplay.getHeight()) {
      float heightRatio = (float) videoHeight
          / (float) currentDisplay.getHeight();
      float widthRatio = (float) videoWidth
          / (float) currentDisplay.getWidth();

      if (heightRatio > 1 || widthRatio > 1) {
        if (heightRatio > widthRatio) {
          videoHeight = (int) Math.ceil((float) videoHeight
              / (float) heightRatio);
          videoWidth = (int) Math.ceil((float) videoWidth
              / (float) heightRatio);
        } else {
          videoHeight = (int) Math.ceil((float) videoHeight
              / (float) widthRatio);
          videoWidth = (int) Math.ceil((float) videoWidth
              / (float) widthRatio);
        }
      }
    }

    surfaceView.setLayoutParams(new LinearLayout.LayoutParams(videoWidth,
        videoHeight));
  }

  public void onBufferingUpdate(MediaPlayer mp, int bufferedPercent) {
    statusView.setText("MediaPlayer Buffering: " + bufferedPercent + "%");
  }
  public boolean canPause() {
    return true;
  }
  public boolean canSeekBackward() {
    return true;
  }
  public boolean canSeekForward() {
    return true;
  }
  public int getBufferPercentage() {
    return 0;
  }
  public int getCurrentPosition() {
    return mediaPlayer.getCurrentPosition();
  }

  public int getDuration() {
    return mediaPlayer.getDuration();
  }
  public boolean isPlaying() {
    return mediaPlayer.isPlaying();
  }
  public void pause() {
    if (mediaPlayer.isPlaying()) {
      mediaPlayer.pause();
    }
  }
  public void seekTo(int pos) {
    mediaPlayer.seekTo(pos);
  }
  public void start() {
    mediaPlayer.start();
  }
  @Override
  public boolean onTouchEvent(MotionEvent ev) {
    if (controller.isShowing()) {
      controller.hide();
    } else {
      controller.show();
    }
    return false;
  }
}

//main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/MainView"
    >
  <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/StatusTextView" android:text="@+id/Status"></TextView>
  <SurfaceView android:id="@+id/SurfaceView" android:layout_height="200dip" android:layout_width="200dip"></SurfaceView> 

</LinearLayout>

Video Gallery

  
package app.test;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class Test extends Activity implements OnItemClickListener {
  Cursor cursor;
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    ListView listView = (ListView) this.findViewById(R.id.ListView);

    String[] thumbColumns = { MediaStore.Video.Thumbnails.DATA,
        MediaStore.Video.Thumbnails.VIDEO_ID };

    String[] mediaColumns = { MediaStore.Video.Media._ID,
        MediaStore.Video.Media.DATA, MediaStore.Video.Media.TITLE,
        MediaStore.Video.Media.MIME_TYPE };

    cursor = managedQuery(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
        mediaColumns, null, null, null);

    ArrayList<VideoViewInfo> videoRows = new ArrayList<VideoViewInfo>();

    if (cursor.moveToFirst()) {
      do {

        VideoViewInfo newVVI = new VideoViewInfo();
        int id = cursor.getInt(cursor.getColumnIndex(MediaStore.Video.Media._ID));
        Cursor thumbCursor = managedQuery(
            MediaStore.Video.Thumbnails.EXTERNAL_CONTENT_URI,
            thumbColumns, MediaStore.Video.Thumbnails.VIDEO_ID
                + "=" + id, null, null);
        if (thumbCursor.moveToFirst()) {
          newVVI.thumbPath = thumbCursor.getString(thumbCursor
              .getColumnIndex(MediaStore.Video.Thumbnails.DATA));
          Log.v("", newVVI.thumbPath);
        }

        newVVI.filePath = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA));
        newVVI.title = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.TITLE));
        Log.v("", newVVI.title);
        newVVI.mimeType = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.MIME_TYPE));
        Log.v("", newVVI.mimeType);
        videoRows.add(newVVI);
      } while (cursor.moveToNext());
    }
    listView.setAdapter(new VideoGalleryAdapter(this, videoRows));
    listView.setOnItemClickListener(this);
  }

  public void onItemClick(AdapterView<?> l, View v, int position, long id) {
    if (cursor.moveToPosition(position)) {
      int fileColumn = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
      int mimeColumn = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.MIME_TYPE);
      String videoFilePath = cursor.getString(fileColumn);
      String mimeType = cursor.getString(mimeColumn);
      Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
      File newFile = new File(videoFilePath);
      intent.setDataAndType(Uri.fromFile(newFile), mimeType);
      startActivity(intent);
    }
  }
}
class VideoViewInfo {
  String filePath;
  String mimeType;
  String thumbPath;
  String title;
}

class VideoGalleryAdapter extends BaseAdapter {
  private Context context;
  private List<VideoViewInfo> videoItems;

  LayoutInflater inflater;

  public VideoGalleryAdapter(Context _context,
      ArrayList<VideoViewInfo> _items) {
    context = _context;
    videoItems = _items;

    inflater = (LayoutInflater) context
        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
  }

  public int getCount() {
    return videoItems.size();
  }

  public Object getItem(int position) {
    return videoItems.get(position);
  }

  public long getItemId(int position) {
    return position;
  }

  public View getView(int position, View convertView, ViewGroup parent) {
    View videoRow = inflater.inflate(R.layout.row, null);
    ImageView videoThumb = (ImageView) videoRow
        .findViewById(R.id.ImageView);
    if (videoItems.get(position).thumbPath != null) {
      videoThumb.setImageURI(Uri
          .parse(videoItems.get(position).thumbPath));
    }

    TextView videoTitle = (TextView) videoRow
        .findViewById(R.id.TextView);
    videoTitle.setText(videoItems.get(position).title);

    return videoRow;
  }
}

//main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
  <ListView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/ListView"></ListView>
</LinearLayout>

//row.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content">
    <ImageView android:id="@+id/ImageView" android:layout_width="wrap_content" android:layout_height="wrap_content"></ImageView>
    <TextView android:text="@+id/TextView01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/TextView"></TextView>
</LinearLayout> 

View Video with VideoView

  
package app.test;

import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.widget.MediaController;
import android.widget.VideoView;

public class Test extends Activity {
  VideoView vv;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    vv = (VideoView) this.findViewById(R.id.VideoView);
    Uri videoUri = Uri
        .parse("rtsp://youtube.com/video.3gp");
    vv.setMediaController(new MediaController(this));
    vv.setVideoURI(videoUri);
    vv.start();
  }
}


//main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<VideoView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/VideoView"></VideoView> 

</LinearLayout>

Video Capture

  
package app.test;

import java.io.IOException;
import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;

public class Test extends Activity implements OnClickListener,
    SurfaceHolder.Callback {
  MediaRecorder recorder;
  SurfaceHolder holder;

  boolean recording = false;
  public static final String TAG = "VIDEOCAPTURE";

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
        WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

    recorder = new MediaRecorder();
    initRecorder();
    setContentView(R.layout.main);

    SurfaceView cameraView = (SurfaceView) findViewById(R.id.CameraView);
    holder = cameraView.getHolder();
    holder.addCallback(this);
    holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

    cameraView.setClickable(true);
    cameraView.setOnClickListener(this);
  }

  private void initRecorder() {
    recorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
    recorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT);

    CamcorderProfile cpHigh = CamcorderProfile
        .get(CamcorderProfile.QUALITY_HIGH);
    recorder.setProfile(cpHigh);
    recorder.setOutputFile("/sdcard/videocapture.mp4");
    recorder.setMaxDuration(50000); // 50 seconds
    recorder.setMaxFileSize(5000000); // Approximately 5 megabytes
  }

  private void prepareRecorder() {
    recorder.setPreviewDisplay(holder.getSurface());

    try {
      recorder.prepare();
    } catch (IllegalStateException e) {
      e.printStackTrace();
      finish();
    } catch (IOException e) {
      e.printStackTrace();
      finish();
    }
  }

  public void onClick(View v) {
    if (recording) {
      recorder.stop();
      recorder.release();
      recording = false;
      Log.v(TAG, "Recording Stopped");
      initRecorder();
      prepareRecorder();
    } else {
      recording = true;
      recorder.start();
    }
  }

  public void surfaceCreated(SurfaceHolder holder) {
    prepareRecorder();
  }

  public void surfaceChanged(SurfaceHolder holder, int format, int width,
      int height) {
  }

  public void surfaceDestroyed(SurfaceHolder holder) {
    if (recording) {
      recorder.stop();
      recording = false;
    }
    recorder.release();
    finish();
  }
}
//main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<SurfaceView android:id="@+id/CameraView" android:layout_width="640px" android:layout_height="480px"></SurfaceView> 

</LinearLayout>

Video Capture with Metadata

  

package app.test;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Test extends Activity implements OnClickListener {

  public static int VIDEO_CAPTURED = 1;

  Button captureVideoButton;
  Button playVideoButton;
  Button saveVideoButton;

  EditText titleEditText;

  Uri videoFileUri;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    captureVideoButton = (Button) this
        .findViewById(R.id.CaptureVideoButton);
    playVideoButton = (Button) this.findViewById(R.id.PlayVideoButton);
    saveVideoButton = (Button) this.findViewById(R.id.SaveVideoButton);

    titleEditText = (EditText) this.findViewById(R.id.TitleEditText);

    captureVideoButton.setOnClickListener(this);
    playVideoButton.setOnClickListener(this);
    saveVideoButton.setOnClickListener(this);

    playVideoButton.setEnabled(false);
    saveVideoButton.setEnabled(false);
    titleEditText.setEnabled(false);
  }

  public void onClick(View v) {
    if (v == captureVideoButton) {
      Intent captureVideoIntent = new Intent(
          android.provider.MediaStore.ACTION_VIDEO_CAPTURE);
      startActivityForResult(captureVideoIntent, VIDEO_CAPTURED);
    } else if (v == playVideoButton) {
      Intent playVideoIntent = new Intent(Intent.ACTION_VIEW,
          videoFileUri);
      startActivity(playVideoIntent);
    } else if (v == saveVideoButton) {

      ContentValues values = new ContentValues(1);
      values.put(MediaStore.MediaColumns.TITLE, titleEditText.getText()
          .toString());

      if (getContentResolver().update(videoFileUri, values, null, null) == 1) {

        Toast t = Toast.makeText(this, "Updated "
            + titleEditText.getText().toString(),
            Toast.LENGTH_SHORT);
        t.show();
      } else {

        Toast t = Toast.makeText(this, "Error", Toast.LENGTH_SHORT);
        t.show();
      }
    }
  }

  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK && requestCode == VIDEO_CAPTURED) {
      videoFileUri = data.getData();
      playVideoButton.setEnabled(true);
      saveVideoButton.setEnabled(true);
      titleEditText.setEnabled(true);
    }
  }
}

//main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
        <Button android:text="Capture Video" android:id="@+id/CaptureVideoButton" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
        <Button android:text="Play Video" android:id="@+id/PlayVideoButton" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
        <TextView android:text="Title:" android:id="@+id/TitleTextView" android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>
        <EditText android:text="" android:id="@+id/TitleEditText" android:layout_width="wrap_content" android:layout_height="wrap_content"></EditText>
        <Button android:text="Save Metadata" android:id="@+id/SaveVideoButton" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button> 

</LinearLayout>

VideoView Demo

package com.example.android.apis.media;

import com.example.android.apis.R;
import android.app.Activity;
import android.os.Bundle;
import android.widget.MediaController;
import android.widget.Toast;
import android.widget.VideoView;

public class VideoViewDemo extends Activity {

    /**
     * TODO: Set the path variable to a streaming video URL or a local media
     * file path.
     */
    private String path = "";
    private VideoView mVideoView;

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.main);
        mVideoView = (VideoView) findViewById(R.id.surface_view);

        if (path == "") {
            // Tell the user to provide a media file URL/path.
            Toast.makeText(
                    VideoViewDemo.this,
                    "Please edit VideoViewDemo Activity, and set path"
                            + " variable to your media file URL/path",
                    Toast.LENGTH_LONG).show();

        } else {

            /*
             * Alternatively,for streaming media you can use
             * mVideoView.setVideoURI(Uri.parse(URLstring));
             */
            mVideoView.setVideoPath(path);
            mVideoView.setMediaController(new MediaController(this));
            mVideoView.requestFocus();

        }
    }
}

//main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >
    
    <VideoView 
        android:id="@+id/surface_view" 
        android:layout_width="320px"
        android:layout_height="240px"
    />
     

</LinearLayout>