1. 程式人生 > >在APP當中呼叫Android系統攝像頭進行視訊錄製

在APP當中呼叫Android系統攝像頭進行視訊錄製

1、獲得攝像頭Feature和寫檔案的許可權

<uses-feature
        android:name="android.hardware.camera2"
        android:required="true" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

2、建立一個檔案用來儲存得到的視訊
<span style="font-size:12px;"> /**
     * 建立保存錄製得到的視訊檔案
     *
     * @return
     * @throws IOException
     */
    private File createMediaFile() throws IOException {
        if (Utils.checkSDCardAvaliable()) {
            File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_MOVIES), "CameraDemo");
            if (!mediaStorageDir.exists()) {
                if (!mediaStorageDir.mkdirs()) {
                    Log.d(TAG, "failed to create directory");
                    return null;
                }
            }
            // Create an image file name
            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
            String imageFileName = "VID_" + timeStamp;
            String suffix = ".mp4";
            File mediaFile = new File(mediaStorageDir + File.separator + imageFileName + suffix);
            return mediaFile;
        }
        return null;
    }</span>
3、啟動Intent進行視訊錄製
 //create new Intent
            Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
            try {
                fileUri = Uri.fromFile(createMediaFile()); // create a file to save the video
            } catch (IOException e) {
                e.printStackTrace();
            }
            intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);  // set the image file name
            intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1); // set the video image quality to high
            // start the Video Capture Intent
            startActivityForResult(intent, CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE);
4、在onActivityResult回撥裡面,通過使用VideoView播放視訊
  @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {
                // Video captured and saved to fileUri specified in the Intent
                Toast.makeText(this, "Video saved to:\n" +
                        data.getData(), Toast.LENGTH_LONG).show();
                //Display the video
                vv_play.setVideoURI(fileUri);
                vv_play.requestFocus();
            } else if (resultCode == RESULT_CANCELED) {
                // User cancelled the video capture
            } else {
                // Video capture failed, advise user
            }
        }
    }
然後,你就可以在你裝置的外部儲存根目錄下的/Movies/CameraDemo/目錄下面找到你錄製的視訊,同時在裝置的相簿裡面發現一個新建項"CameraDemo",裡面有你錄製的視訊。在根目錄下的/Movies目錄的檔案是會自動被media scanner進行掃描的,當然我們也可以手動觸發系統的media scanner進行掃描,這樣就會立即生效。