在Single Activity中预览多个图像和视频

时间:2014-06-20 06:36:56

标签: android video imageview android-videoview

我试图在单一动作中显示两个ImageView。这些Imageview由视频帧组成。当它们被点击时,相应的视频开始播放。但问题是当我捕获第一个视频并返回主动作时没有显示图像当我拍摄第二个视频并返回主要活动图像时,会显示第一个视频的预览。当我点击它时,只显示黑屏,当我使用单个VideoView和单个ImageView进行单个视频时,它工作正常。我正在使用fileUri和fileUri1来存储视频的路径。布局中是否存在问题或某些编程错误或视图定位?

1 个答案:

答案 0 :(得分:1)

Try this way,hope this will help you to solve your problem.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:gravity="center"
        android:orientation="vertical" >

        <!-- Capture picture button -->
        <Button
            android:id="@+id/btnCapturePicture"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Take a Picture"
            android:layout_marginBottom="10dp"/>

        <!-- Record video button -->
        <Button
            android:id="@+id/btnRecordVideo"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Record a Video"
            android:layout_marginBottom="10dp"/>

        <Button
            android:id="@+id/See"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="See Video" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:orientation="vertical"
        android:padding="10dp">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Preview"
            android:padding="10dp"
            android:textSize="15dp"/>

        <!-- To display picture taken -->
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:orientation="vertical"
            android:layout_marginTop="10dp"
            android:layout_marginBottom="10dp">
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight="1"
                android:layout_marginBottom="10dp">
                <ImageView
                    android:id="@+id/imgPreview"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:adjustViewBounds="true"
                    android:visibility="gone" />
            </LinearLayout>
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight="1">
                <ImageView
                    android:id="@+id/imgPreview2"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:adjustViewBounds="true"
                    android:visibility="gone"/>
            </LinearLayout>
        </LinearLayout>
        <!-- To preview video recorded -->
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:orientation="vertical"
            android:layout_marginTop="10dp">
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight="1"
                android:layout_marginBottom="10dp">
                <VideoView
                    android:id="@+id/videoPreview"
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:visibility="gone"/>
            </LinearLayout>
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight="1">
                <VideoView
                    android:id="@+id/videoView2"
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:visibility="gone"/>
            </LinearLayout>
        </LinearLayout>
    </LinearLayout>

</LinearLayout>

public class MainActivity extends Activity {


    private static final int CAMERA_CAPTURE_VIDEO_REQUEST_CODE = 200;

    public static final int MEDIA_TYPE_VIDEO = 2;

    // directory name to store captured images and videos
    private static final String IMAGE_DIRECTORY_NAME = "Hello Camera";

    public static Uri fileUri=null;
    public static Uri fileUri1=null;// file url to store image/video

    private ImageView imgPreview,imgPreview2;
    private VideoView videoPreview,videoPreview2;
    private Button btnCapturePicture, btnRecordVideo,btnSee;
    private int countClick;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        imgPreview = (ImageView) findViewById(R.id.imgPreview);
        imgPreview2 = (ImageView) findViewById(R.id.imgPreview2);
        videoPreview = (VideoView) findViewById(R.id.videoPreview);
        videoPreview2 = (VideoView) findViewById(R.id.videoView2);

        btnRecordVideo = (Button) findViewById(R.id.btnRecordVideo);
        btnSee = (Button) findViewById(R.id.See);


        countClick=0;
        btnRecordVideo.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // record video
                countClick++;
                recordVideo();
            }
        });
        btnSee.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // capture picture

                Intent i= new Intent();

                //Uri uri = i.getParcelableExtra("fileUri");
                i.putExtra ("fileuri",fileUri);
                //i.putExtra ("fileuri1",fileUri1);
                i.setClass(getApplicationContext(), SecondActivity.class);
                startActivity(i);
            }
        });

        // Checking camera availability
        if (!isDeviceSupportCamera()) {
            Toast.makeText(getApplicationContext(),
                    "Sorry! Your device doesn't support camera",
                    Toast.LENGTH_LONG).show();
            // will close the app if the device does't have camera
            finish();
        }
    }

    /**
     * Checking device has camera hardware or not
     * */
    private boolean isDeviceSupportCamera() {
        if (getApplicationContext().getPackageManager().hasSystemFeature(
                PackageManager.FEATURE_CAMERA)) {
            // this device has a camera
            return true;
        } else {
            // no camera on this device
            return false;
        }
    }



    /*
     * Here we store the file url as it will be null after returning from camera
     * app
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        // save file url in bundle as it will be null on scren orientation
        // changes
        outState.putParcelable("file_uri", fileUri);
        //outState.putParcelable("file_uri", fileUri1);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);

        // get the file url
        fileUri = savedInstanceState.getParcelable("file_uri");
        //fileUri1 = savedInstanceState.getParcelable("file_uri1");
    }

    /*
     * Recording video
     */
    private void recordVideo() {
        Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
        if(countClick%2==0){
            fileUri1 = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);



            // set video quality
            intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);

            intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri1); // set the image file
            // name
            intent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 20);
            // start the video capture Intent
            startActivityForResult(intent, CAMERA_CAPTURE_VIDEO_REQUEST_CODE);
        }else{
            fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);

            // set video quality
            intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);

            intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file
            // name
            intent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 20);
            // start the video capture Intent
            startActivityForResult(intent, CAMERA_CAPTURE_VIDEO_REQUEST_CODE);



        }

    }




    /**
     * Receiving activity result method will be called after closing the camera
     * */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // if the result is capturing Image
        if (requestCode == CAMERA_CAPTURE_VIDEO_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {
                // video successfully recorded
                // preview the recorded video
                previewVideo();
            } else if (resultCode == RESULT_CANCELED) {
                // user cancelled recording
                Toast.makeText(getApplicationContext(),
                        "User cancelled video recording", Toast.LENGTH_SHORT)
                        .show();
            } else {
                // failed to record video
                Toast.makeText(getApplicationContext(),
                        "Sorry! Failed to record video", Toast.LENGTH_SHORT)
                        .show();
            }
        }
    }



    /*
     * Previewing recorded video
     */
    private void previewVideo() {
        try {
            // hide image preview
            //if(fileUri==null)
            //{
            /*imgPreview.setVisibility(View.GONE);

            videoPreview.setVisibility(View.VISIBLE);
            videoPreview.setVideoPath(fileUri.getPath());
            // start playing
            videoPreview.start();*/
            /*videoPreview.setVisibility(View.GONE);

            imgPreview.setVisibility(View.VISIBLE);
            Bitmap bmThumbnail;
            bmThumbnail = ThumbnailUtils.createVideoThumbnail(fileUri.getPath() , 
                       Thumbnails.MICRO_KIND);
            imgPreview.setImageBitmap(bmThumbnail);*/
            videoPreview.setVisibility(View.GONE);
            videoPreview2.setVisibility(View.GONE);  //both videoviews are made invisible and both imageviews are made visible

            if(countClick>=2){
                imgPreview.setVisibility(View.VISIBLE);
                imgPreview2.setVisibility(View.VISIBLE);
                MediaMetadataRetriever retriever = new MediaMetadataRetriever();
                MediaMetadataRetriever retriever1 = new MediaMetadataRetriever();
                retriever.setDataSource(fileUri.getPath());
                retriever1.setDataSource(fileUri1.getPath());
                Bitmap myBitmap = retriever.getFrameAtTime(1000000);
                Bitmap myBitmap1 = retriever1.getFrameAtTime(1000000);
                imgPreview.setImageBitmap(myBitmap);
                imgPreview2.setImageBitmap(myBitmap1);
            }else{
                imgPreview.setVisibility(View.VISIBLE);
                MediaMetadataRetriever retriever = new MediaMetadataRetriever();
                retriever.setDataSource(fileUri.getPath());
                Bitmap myBitmap = retriever.getFrameAtTime(1000000);
                imgPreview.setImageBitmap(myBitmap);
            }



            imgPreview.setOnClickListener(new View.OnClickListener() { //clicking on first imageView

                @Override
                public void onClick(View v) {
                    imgPreview.setVisibility(View.GONE);
                    imgPreview2.setVisibility(View.GONE);
                    videoPreview.setVisibility(View.VISIBLE); //first videoview video starts playing
                    videoPreview2.setVisibility(View.GONE);

                    videoPreview.setVideoPath(fileUri.getPath());

                    videoPreview.start();

                }


            });
            imgPreview2.setOnClickListener(new View.OnClickListener() { //clicking on secong imageview

                @Override
                public void onClick(View v) {
                    imgPreview2.setVisibility(View.GONE);
                    imgPreview.setVisibility(View.GONE);
                    videoPreview2.setVisibility(View.VISIBLE); //second videoview video starts playing
                    videoPreview.setVisibility(View.GONE);
                    videoPreview2.setVideoPath(fileUri1.getPath());

                    videoPreview2.start();
                }


            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * ------------ Helper Methods ----------------------
     * */

    /*
     * Creating file uri to store image/video
     */
    public Uri getOutputMediaFileUri(int type) {
        return Uri.fromFile(getOutputMediaFile(type));
    }

    /*
     * returning image / video
     */
    private static File getOutputMediaFile(int type) {

        // External sdcard location
        File mediaStorageDir = new File(
                Environment
                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                IMAGE_DIRECTORY_NAME);

        // Create the storage directory if it does not exist
        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create "
                        + IMAGE_DIRECTORY_NAME + " directory");
                return null;
            }
        }

        // Create a media file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
                Locale.getDefault()).format(new Date());
        File mediaFile;
        /*if (type == MEDIA_TYPE_IMAGE) {
            mediaFile = new File(mediaStorageDir.getPath() + File.separator
                    + "IMG_" + timeStamp + ".jpg");
        } else*/ if (type == MEDIA_TYPE_VIDEO) {
            mediaFile = new File(mediaStorageDir.getPath() + File.separator
                    + "VID_" + timeStamp + ".mp4");
        } else {
            return null;
        }

        return mediaFile;
    }
}