android.media.MediaRecorder#prepare ( )源码实例Demo

下面列出了android.media.MediaRecorder#prepare ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: droid-stealth   文件: RecorderActivity.java
/**
 * Starts the media recorder to record a new fragment
 */
private void startRecording() {
	mRecorder = new MediaRecorder();
	mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
	mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
	mRecorder.setOutputFile(FileUtils.getPath(this, mOutputUri));
	mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
	try {
		mRecorder.prepare();
	}
	catch (IOException e) {
		Utils.d("Error writing file: "+e.toString());
		Toast.makeText(getApplicationContext(), "An error occured at recorder preparations.", Toast.LENGTH_LONG)
				.show();
	}

	mRecorder.start();
	mVolumeChecker.run();
}
 
private void startAndSaveRecord(File recordFile) {
    stopRecord();
    mMediaRecorder = new MediaRecorder();
    mMediaRecorder.reset();
    // TODO: 16.05.17 not working well
    mMediaRecorder.setAudioSource(mPreferenceHelper.getAudioSource());   //or default voice_communication
    mMediaRecorder.setOutputFormat(mPreferenceHelper.getOutputFormat()); //MP4
    mMediaRecorder.setAudioEncoder(mPreferenceHelper.getAudioEncoder()); //AAC
    mMediaRecorder.getMaxAmplitude();
    try {
        if (!recordFile.createNewFile()) {
            Log.i(TAG, "File name has been already given");
        }
        mMediaRecorder.setOutputFile(recordFile.getAbsolutePath());
        mMediaRecorder.prepare();
        mMediaRecorder.start();
    } catch (IOException e) {
        Log.e(TAG, "Error: Recording could not be starting!", e);
    }
}
 
public void startRecording(View view) throws IOException {

		startButton.setEnabled(false);
		stopButton.setEnabled(true);

		File sampleDir = Environment.getExternalStorageDirectory();
		try {
			audiofile = File.createTempFile("sound", ".3gp", sampleDir);
		} catch (IOException e) {
			Log.e(TAG, "sdcard access error");
			return;
		}
		recorder = new MediaRecorder();
		recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
		recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
		recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
		recorder.setOutputFile(audiofile.getAbsolutePath());
		recorder.prepare();
		recorder.start();
	}
 
源代码4 项目: VideoRecorderTest   文件: MainActivity.java
private boolean prepareMediaRecorder() {
    mMediaRecorder = new MediaRecorder();
    mCamera.unlock();
    mMediaRecorder.setCamera(mCamera);
    mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
    mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
    mMediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_1080P));
    mMediaRecorder.setPreviewDisplay(mHolder.getSurface());
    String path = getSDPath();
    if (path != null) {

        File dir = new File(path + "/VideoRecorderTest");
        if (!dir.exists()) {
            dir.mkdir();
        }
        path = dir + "/" + getDate() + ".mp4";
        mMediaRecorder.setOutputFile(path);
        try {
            mMediaRecorder.prepare();
        } catch (IOException e) {
            releaseMediaRecorder();
            e.printStackTrace();
        }
    }
    return true;
}
 
源代码5 项目: qiscus-sdk-android   文件: QiscusAudioRecorder.java
private void startRecording(String fileName) throws IOException {
    if (!recording) {
        this.fileName = fileName;
        recording = true;
        recorder = new MediaRecorder();
        recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
        recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
        recorder.setOutputFile(fileName);
        recorder.prepare();
        recorder.start();
    }
}
 
源代码6 项目: ui   文件: noxmllayoutexample.java
private void startRecording() {
    mRecorder = new MediaRecorder();
    mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
    mRecorder.setOutputFile(mFileName);
    mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

    try {
        mRecorder.prepare();
    } catch (IOException e) {
        Log.e(LOG_TAG, "prepare() failed");
    }

    mRecorder.start();
}
 
public void recordVideo(VideoStartCallback videoStartCallback, VideoStopCallback videoStopCallback, VideoErrorCallback videoErrorCallback) {
    try {
        this.videoStartCallback = videoStartCallback;
        this.videoStopCallback = videoStopCallback;
        this.videoErrorCallback = videoErrorCallback;
        if (mCameraDevice == null || !mTextureView.isAvailable() || mPreviewSize == null) {
            this.videoErrorCallback.onVideoError("Camera not ready.");
            return;
        }
        videoFile = Environment.getExternalStorageDirectory() + "/" + formatter.format(new Date()) + ".mp4";
        mMediaRecorder = new MediaRecorder();
        //mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
        mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
        mMediaRecorder.setOutputFile(videoFile);
        mMediaRecorder.setVideoEncodingBitRate(10000000);
        mMediaRecorder.setVideoFrameRate(30);
        mMediaRecorder.setVideoSize(mVideoSize.getWidth(), mVideoSize.getHeight());
        mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
        //mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
        if (swappedDimensions) {
            mMediaRecorder.setOrientationHint(INVERSE_ORIENTATIONS.get(mDisplayOrientation));
        } else {
            mMediaRecorder.setOrientationHint(ORIENTATIONS.get(mDisplayOrientation));
        }
        mMediaRecorder.prepare();
        closePreviewSession();
        createCameraRecordSession();
    } catch (IOException ex) {
        Log.d(TAG, "Video Recording error"+ex.getMessage());
    }
}
 
源代码8 项目: AlbumCameraRecorder   文件: RecordingService.java
private void startRecording() {

        // 根据配置创建文件配置
        GlobalSpec globalSpec = GlobalSpec.getInstance();
        mAudioMediaStoreCompat = new MediaStoreCompat(getApplicationContext());
        mAudioMediaStoreCompat.setSaveStrategy(globalSpec.audioStrategy == null ? globalSpec.saveStrategy : globalSpec.audioStrategy);

        setFileNameAndPath();

        mRecorder = new MediaRecorder();
        mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        mRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
        mRecorder.setOutputFile(mFile.getPath());
        mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
        mRecorder.setAudioChannels(1);
        if (MySharedPreferences.getPrefHighQuality(this)) {
            mRecorder.setAudioSamplingRate(44100);
            mRecorder.setAudioEncodingBitRate(192000);
        }

        try {
            mRecorder.prepare();
            mRecorder.start();
            mStartingTimeMillis = System.currentTimeMillis();

            //startTimer();
            //startForeground(1, createNotification());

        } catch (IOException e) {
            Log.e(LOG_TAG, "prepare() failed");
        }
    }
 
private void startRecording() {
    recording = true;
    mRecorder = new MediaRecorder();
    mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    mRecorder.setOutputFormat(MediaRecorder.OutputFormat.AAC_ADTS);
    mRecorder.setOutputFile(mFilePath);
    mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
    try {
        mRecorder.prepare();
        final Animation animation = new AlphaAnimation(1, (float)0.5); // Change alpha from fully visible to invisible
        animation.setDuration(500); // duration - half a second
        animation.setInterpolator(new LinearInterpolator()); // do not alter animation rate
        animation.setRepeatCount(Animation.INFINITE); // Repeat animation infinitely
        animation.setRepeatMode(Animation.REVERSE); // Reverse animation at the end so the button will fade back in
        btnRecord.startAnimation(animation);
        startTime = System.currentTimeMillis();
        AudioNoteActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (mRecorder != null) {
                    long time = System.currentTimeMillis() - startTime;
                    int seconds = (int) time / 1000;
                    int minutes = seconds / 60;
                    seconds = seconds % 60;
                    tvRecordingTime.setText(String.format("%02d", minutes) + ":" + String.format("%02d", seconds));
                    mHandler.postDelayed(this, 100);
                }
            }
        });

        mRecorder.start();
    } catch (IOException e) {
        recording = false;
        e.printStackTrace();
    }
}
 
源代码10 项目: Camera2Vision   文件: Camera2Source.java
public void recordVideo(VideoStartCallback videoStartCallback, VideoStopCallback videoStopCallback, VideoErrorCallback videoErrorCallback) {
    try {
        this.videoStartCallback = videoStartCallback;
        this.videoStopCallback = videoStopCallback;
        this.videoErrorCallback = videoErrorCallback;
        if(mCameraDevice == null || !mTextureView.isAvailable() || mPreviewSize == null){
            this.videoErrorCallback.onVideoError("Camera not ready.");
            return;
        }
        videoFile = Environment.getExternalStorageDirectory() + "/" + formatter.format(new Date()) + ".mp4";
        mMediaRecorder = new MediaRecorder();
        //mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
        mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
        mMediaRecorder.setOutputFile(videoFile);
        mMediaRecorder.setVideoEncodingBitRate(10000000);
        mMediaRecorder.setVideoFrameRate(30);
        mMediaRecorder.setVideoSize(mVideoSize.getWidth(), mVideoSize.getHeight());
        mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
        //mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
        if(swappedDimensions) {
            mMediaRecorder.setOrientationHint(INVERSE_ORIENTATIONS.get(mDisplayOrientation));
        } else {
            mMediaRecorder.setOrientationHint(ORIENTATIONS.get(mDisplayOrientation));
        }
        mMediaRecorder.prepare();
        closePreviewSession();
        createCameraRecordSession();
    } catch(IOException ex) {
        Log.d(TAG, ex.getMessage());
    }
}
 
源代码11 项目: CameraView   文件: JCameraView.java
private void startRecord() {
    mediaRecorder = new MediaRecorder();
    mediaRecorder.reset();
    mCamera.unlock();
    // 设置录制视频源为Camera(相机)
    mediaRecorder.setCamera(mCamera);
    mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
    mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    // 设置录制完成后视频的封装格式THREE_GPP为3gp.MPEG_4为mp4
    mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
    // 设置录制的视频编码h263 h264
    mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
    mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
    // 设置视频录制的分辨率。必须放在设置编码和格式的后面,否则报错
    mediaRecorder.setVideoSize(width, height);
    // 设置录制的视频帧率。必须放在设置编码和格式的后面,否则报错
    if (SELECTED_CAMERA == CAMERA_FRONT_POSITION) {
        mediaRecorder.setOrientationHint(270);
    } else {
        mediaRecorder.setOrientationHint(90);
    }
    mediaRecorder.setMaxDuration(10000);
    mediaRecorder.setVideoEncodingBitRate(5 * 1024 * 1024);
    mediaRecorder.setVideoFrameRate(20);
    mediaRecorder.setPreviewDisplay(mHolder.getSurface());
    // 设置视频文件输出的路径
    mediaRecorder.setOutputFile("/sdcard/love.mp4");
    try {
        //准备录制
        mediaRecorder.prepare();
        // 开始录制
        mediaRecorder.start();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
源代码12 项目: GravityBox   文件: RecordingService.java
private void startRecording() {
    String statusMessage = "";
    String audioFileName = prepareOutputFile();
    try {
        mRecorder = new MediaRecorder();
        mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        mRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
        mRecorder.setOutputFile(audioFileName);
        mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
        mRecorder.setAudioEncodingBitRate(96000);
        mRecorder.setAudioSamplingRate(mSamplingRate);
        mRecorder.setOnErrorListener(mOnErrorListener);
        mRecorder.prepare();
        mRecorder.start();
        mRecordingStatus = RECORDING_STATUS_STARTED;
        startForeground(1, mRecordingNotif);
    } catch (Exception e) {
        e.printStackTrace();
        mRecordingStatus = RECORDING_STATUS_ERROR;
        statusMessage = e.getMessage();
    } finally {
        Intent i = new Intent(ACTION_RECORDING_STATUS_CHANGED);
        i.putExtra(EXTRA_RECORDING_STATUS, mRecordingStatus);
        if (mRecordingStatus == RECORDING_STATUS_STARTED) {
            i.putExtra(EXTRA_AUDIO_FILENAME, audioFileName);
        }
        i.putExtra(EXTRA_STATUS_MESSAGE, statusMessage); 
        sendBroadcast(i);
    }
}
 
源代码13 项目: PlayTogether   文件: AudioManager.java
/**
 * 准备录音
 */
public void prepareAudio()
{
	try
	{
		isPrepare = false;
		File dir = new File(mDir);
		if (!dir.exists())
			dir.mkdirs();
		String fileName = UUID.randomUUID() + ".amr";
		mFile = new File(dir, fileName);
		mMediaRecorder = new MediaRecorder();
		mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
		mMediaRecorder.setOutputFile(mFile.getAbsolutePath());
		mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
		mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
		mMediaRecorder.prepare();
		mMediaRecorder.start();
		isPrepare = true;
		if (mAudioStateListener != null)
		{
			mAudioStateListener.hadPrepare();
		}
	} catch (Exception e)
	{
		e.printStackTrace();
		isPrepare = false;
	}
}
 
源代码14 项目: astrobee_android   文件: MainActivity.java
public void onRecordClick(View v) {
    if (!mRecording) {
        File f = new File(getExternalFilesDir(null), "recording.mp4");

        mRecorder = new MediaRecorder();
        mRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
        mRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
        mRecorder.setOutputFile(f.getAbsolutePath());
        mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC_ELD);
        mRecorder.setAudioSamplingRate(48000);
        mRecorder.setAudioEncodingBitRate(96000);

        try {
            mRecorder.prepare();
        } catch (IOException e) {
            Log.e(TAG, "unable to prepare MediaRecorder");
            mRecorder = null;
            return;
        }

        mRecorder.start();
        mRecording = true;

        setState(STATE_RECORDING);
    } else {
        mRecorder.stop();
        mRecorder.release();
        mRecording = false;

        setState(STATE_IDLE);
    }
}
 
源代码15 项目: glass_snippets   文件: CameraService.java
@Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
	camera = Camera.open();
	try {
		mediaRecorder = new MediaRecorder();

		List<int[]> fps = camera.getParameters().getSupportedPreviewFpsRange();
		int preview_fps[] = fps.get(0);

		for (int i[] : camera.getParameters().getSupportedPreviewFpsRange())
			preview_fps = (mCaptureRate <= i[1] && mCaptureRate > i[0]) ? i : preview_fps;

		Camera.Parameters param = camera.getParameters();
		param.setVideoStabilization(true);
		param.setPreviewFpsRange(preview_fps[0], preview_fps[1]);
		camera.setParameters(param);
		camera.unlock();

		mediaRecorder.setPreviewDisplay(surfaceHolder.getSurface());
		mediaRecorder.setCamera(camera);

		mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
		CamcorderProfile profile;
		if (mCaptureRate > 25) {
			mediaRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
			profile = CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH);
		} else {
			profile = CamcorderProfile.get(CamcorderProfile.QUALITY_TIME_LAPSE_HIGH);
			mediaRecorder.setCaptureRate(mCaptureRate);
			profile.videoFrameRate = ((int) Math.ceil(mCaptureRate));
		}

		mediaRecorder.setProfile(profile);
		mediaRecorder.setOutputFile(mOutFile);

		mediaRecorder.prepare();
		mediaRecorder.start();

		ScaleAnimation a = new ScaleAnimation(3, 2, 3, 2);
		a.setDuration(2000);
		surfaceView.startAnimation(a);

		Log.i(TAG, String.format("recording %s with rate %.2f", mOutFile, mCaptureRate));
	} catch(Exception e) {
		onDestroy();
		Log.d(TAG, e.toString());
	}
}
 
源代码16 项目: SimpleVideoEditor   文件: Camera2.java
private boolean prepareMediaRecorder() {
        // 默认使用最高质量拍摄
        CamcorderProfile profile =
                CamcorderProfile.
                        get(Integer.valueOf((String) mConfig.getCurrentCameraId()), CamcorderProfile.QUALITY_720P);

        Size previewSize = chooseOptimalSize();

        mMediaRecorder = new MediaRecorder();
        mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
        mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);

        mMediaRecorder.setOutputFormat(profile.fileFormat);

        mMediaRecorder.setVideoFrameRate(profile.videoFrameRate);
//        mMediaRecorder.setVideoSize(mAspectRatio.getX(), mAspectRatio.getY());
//        mMediaRecorder.setVideoSize(profile.videoFrameWidth, profile.videoFrameHeight);
        mMediaRecorder.setVideoSize(previewSize.getWidth(), previewSize.getHeight());
        @SuppressWarnings("ConstantConditions")
        int sensorOrientation = mCameraCharacteristics.get(
                CameraCharacteristics.SENSOR_ORIENTATION);
        int rotation = (sensorOrientation +
                mDisplayOrientation * (mConfig.getCurrentFacing() == Constants.CAMERA_FACING_FRONT ? 1 : -1) +
                360) % 360;
        mMediaRecorder.setOrientationHint(rotation);
        mMediaRecorder.setVideoEncodingBitRate(profile.videoBitRate);
        mMediaRecorder.setVideoEncoder(profile.videoCodec);

        mMediaRecorder.setAudioEncodingBitRate(profile.audioBitRate);
        mMediaRecorder.setAudioChannels(profile.audioChannels);
        mMediaRecorder.setAudioSamplingRate(profile.audioSampleRate);
        mMediaRecorder.setAudioEncoder(profile.audioCodec);

        mMediaRecorder.setOutputFile(mConfig.getResultFile().getAbsolutePath());

        // 如果针对拍摄的文件大小和拍摄时间有设置的话,也可以在这里设置

        try {
            mMediaRecorder.prepare();

            return true;
        } catch (Exception e) {
            Log.d(TAG, "prepareMediaRecorder: " + e);
        }

        // 这个时候出现了错误,应该释放有关资源
        releaseVideoRecorder();
        return false;
    }
 
源代码17 项目: libstreaming   文件: AudioStream.java
@Override
protected void encodeWithMediaRecorder() throws IOException {
	
	// We need a local socket to forward data output by the camera to the packetizer
	createSockets();

	Log.v(TAG,"Requested audio with "+mQuality.bitRate/1000+"kbps"+" at "+mQuality.samplingRate/1000+"kHz");
	
	mMediaRecorder = new MediaRecorder();
	mMediaRecorder.setAudioSource(mAudioSource);
	mMediaRecorder.setOutputFormat(mOutputFormat);
	mMediaRecorder.setAudioEncoder(mAudioEncoder);
	mMediaRecorder.setAudioChannels(1);
	mMediaRecorder.setAudioSamplingRate(mQuality.samplingRate);
	mMediaRecorder.setAudioEncodingBitRate(mQuality.bitRate);
	
	// We write the output of the camera in a local socket instead of a file !			
	// This one little trick makes streaming feasible quiet simply: data from the camera
	// can then be manipulated at the other end of the socket
	FileDescriptor fd = null;
	if (sPipeApi == PIPE_API_PFD) {
		fd = mParcelWrite.getFileDescriptor();
	} else  {
		fd = mSender.getFileDescriptor();
	}
	mMediaRecorder.setOutputFile(fd);
	mMediaRecorder.setOutputFile(fd);

	mMediaRecorder.prepare();
	mMediaRecorder.start();

	InputStream is = null;
	
	if (sPipeApi == PIPE_API_PFD) {
		is = new ParcelFileDescriptor.AutoCloseInputStream(mParcelRead);
	} else  {
		try {
			// mReceiver.getInputStream contains the data from the camera
			is = mReceiver.getInputStream();
		} catch (IOException e) {
			stop();
			throw new IOException("Something happened with the local sockets :/ Start failed !");
		}
	}

	// the mPacketizer encapsulates this stream in an RTP stream and send it over the network
	mPacketizer.setInputStream(is);
	mPacketizer.start();
	mStreaming = true;
	
}
 
源代码18 项目: Fatigue-Detection   文件: CameraEngine.java
private boolean prepareMediaRecorder() {
        try {
           // final Activity activity = getActivity();
            //if (null == activity) return false;
            //final BaseCaptureInterface captureInterface = (BaseCaptureInterface) activity;

           // setCameraDisplayOrientation(mCamera.getParameters());
            mMediaRecorder = new MediaRecorder();
            camera.stopPreview();
            camera.unlock();
            mMediaRecorder.setCamera(camera);

  //          boolean canUseAudio = true;
            //boolean audioEnabled = !mInterface.audioDisabled();
            //if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
            //    canUseAudio = ContextCompat.checkSelfPermission(activity, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED;

//            if (canUseAudio && audioEnabled) {
                mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
//            } else if (audioEnabled) {
//                Toast.makeText(getActivity(), R.string.mcam_no_audio_access, Toast.LENGTH_LONG).show();
//            }
            mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT);

            final CamcorderProfile profile = CamcorderProfile.get(currentCameraId, CamcorderProfile.QUALITY_HIGH);
            mMediaRecorder.setOutputFormat(profile.fileFormat);
            mMediaRecorder.setVideoFrameRate(profile.videoFrameRate);
            mMediaRecorder.setVideoSize(previewSize.width, previewSize.height);
            mMediaRecorder.setVideoEncodingBitRate(profile.videoBitRate);
            mMediaRecorder.setVideoEncoder(profile.videoCodec);

            mMediaRecorder.setAudioEncodingBitRate(profile.audioBitRate);
            mMediaRecorder.setAudioChannels(profile.audioChannels);
            mMediaRecorder.setAudioSamplingRate(profile.audioSampleRate);
            mMediaRecorder.setAudioEncoder(profile.audioCodec);


            Uri uri = Uri.fromFile(FileUtils.makeTempFile(
                    new File(Environment.getExternalStorageDirectory(),
                            "/Omoshiroi/videos").getAbsolutePath(),
                    "VID_", ".mp4"));

            mMediaRecorder.setOutputFile(uri.getPath());

//            if (captureInterface.maxAllowedFileSize() > 0) {
//                mMediaRecorder.setMaxFileSize(captureInterface.maxAllowedFileSize());
//                mMediaRecorder.setOnInfoListener(new MediaRecorder.OnInfoListener() {
//                    @Override
//                    public void onInfo(MediaRecorder mediaRecorder, int what, int extra) {
//                        if (what == MediaRecorder.MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED) {
//                            Toast.makeText(getActivity(), R.string.mcam_file_size_limit_reached, Toast.LENGTH_SHORT).show();
//                            stopRecordingVideo(false);
//                        }
//                    }
//                });
//            }

            mMediaRecorder.setOrientationHint(90);
     //       mMediaRecorder.setPreviewDisplay(mPreviewView.getHolder().getSurface());

            mMediaRecorder.prepare();
            return true;

        } catch (Exception e) {
            camera.lock();
            e.printStackTrace();
            return false;
        }
    }
 
private void setUpMediaRecorder(final File outputFile) throws IOException {
    int rotation = getWindowManager().getDefaultDisplay().getRotation();

    mMediaRecorder = new MediaRecorder();
    mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
    mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
    mMediaRecorder.setOutputFile(outputFile.getAbsolutePath());
    mMediaRecorder.setVideoEncodingBitRate(10000000);
    mMediaRecorder.setVideoFrameRate(30);
    mMediaRecorder.setVideoSize(mVideoSize.getWidth(), mVideoSize.getHeight());
    mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
    mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
    int hint;
    SparseIntArray orientations;
    if (mFacing == Camera2Recorder.CameraFacing.FRONT) {
        switch (rotation) {
            case Surface.ROTATION_0:
                rotation = Surface.ROTATION_0;
                break;
            case Surface.ROTATION_90:
                rotation = Surface.ROTATION_270;
                break;
            case Surface.ROTATION_180:
                rotation = Surface.ROTATION_180;
                break;
            case Surface.ROTATION_270:
                rotation = Surface.ROTATION_90;
                break;
        }
    }
    switch (mSensorOrientation) {
        case SENSOR_ORIENTATION_INVERSE_DEGREES:
            orientations = INVERSE_ORIENTATIONS;
            break;
        case SENSOR_ORIENTATION_DEFAULT_DEGREES:
        default:
            orientations = DEFAULT_ORIENTATIONS;
            break;
    }
    hint = orientations.get(rotation);
    mMediaRecorder.setOrientationHint(hint);
    mMediaRecorder.prepare();
    if (DEBUG) {
        Log.d(TAG, "VideoSize: " + mVideoSize.getWidth() + "x" + mVideoSize.getHeight());
        Log.d(TAG, "OutputFile: " + outputFile.getAbsolutePath());
        Log.d(TAG, "Facing: " + mFacing.getName());
        Log.d(TAG, "SensorOrientation: " + mSensorOrientation);
        Log.d(TAG, "DisplayRotation: " + rotation);
        Log.d(TAG, "OrientationHint: " + hint);
    }
}
 
源代码20 项目: WhatsAppCamera   文件: WhatsappCameraActivity.java
@SuppressLint("SimpleDateFormat")
protected boolean prepareMediaRecorder() throws IOException {

    mediaRecorder = new MediaRecorder(); // Works well
    camera.stopPreview();
    camera.unlock();
    mediaRecorder.setCamera(camera);
    mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
    mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    if (flag == 1) {
        mediaRecorder.setProfile(CamcorderProfile.get(1, CamcorderProfile.QUALITY_HIGH));
    } else {
        mediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));
    }
    mediaRecorder.setPreviewDisplay(surfaceHolder.getSurface());

    mediaRecorder.setOrientationHint(mOrientation);

    if (Build.MODEL.equalsIgnoreCase("Nexus 6") && flag == 1) {

        if (mOrientation == 90) {
            mediaRecorder.setOrientationHint(mOrientation);
        } else if (mOrientation == 180) {
            mediaRecorder.setOrientationHint(0);
        } else {
            mediaRecorder.setOrientationHint(180);
        }

    } else if (mOrientation == 90 && flag == 1) {
        mediaRecorder.setOrientationHint(270);
    } else if (flag == 1) {
        mediaRecorder.setOrientationHint(mOrientation);
    }
    mediaFileName = "wc_vid_" + System.currentTimeMillis();
    mediaRecorder.setOutputFile(folder.getAbsolutePath() + "/" + mediaFileName + ".mp4"); // Environment.getExternalStorageDirectory()

    mediaRecorder.setOnInfoListener(new MediaRecorder.OnInfoListener() {

        public void onInfo(MediaRecorder mr, int what, int extra) {
            // TODO Auto-generated method stub

            if (what == MediaRecorder.MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED) {

                long downTime = 0;
                long eventTime = 0;
                float x = 0.0f;
                float y = 0.0f;
                int metaState = 0;
                MotionEvent motionEvent = MotionEvent.obtain(
                        downTime,
                        eventTime,
                        MotionEvent.ACTION_UP,
                        0,
                        0,
                        metaState
                );

                imgCapture.dispatchTouchEvent(motionEvent);

                Toast.makeText(WhatsappCameraActivity.this, "You reached to Maximum(25MB) video size.", Toast.LENGTH_SHORT).show();
            }


        }
    });

    mediaRecorder.setMaxFileSize(1000 * 25 * 1000);

    try {
        mediaRecorder.prepare();
    } catch (Exception e) {
        releaseMediaRecorder();
        e.printStackTrace();
        return false;
    }
    return true;

}