Java Code Examples for android.media.MediaRecorder#prepare()

The following examples show how to use android.media.MediaRecorder#prepare() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RecordService.java    From android-auto-call-recorder with MIT License 6 votes vote down vote up
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);
    }
}
 
Example 2
Source File: SoundRecordingActivity.java    From codeexamples-android with Eclipse Public License 1.0 6 votes vote down vote up
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();
	}
 
Example 3
Source File: RecorderActivity.java    From droid-stealth with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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();
}
 
Example 4
Source File: MainActivity.java    From VideoRecorderTest with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 5
Source File: AudioNoteActivity.java    From privacy-friendly-notes with GNU General Public License v3.0 5 votes vote down vote up
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();
    }
}
 
Example 6
Source File: MainActivity.java    From astrobee_android with Apache License 2.0 5 votes vote down vote up
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);
    }
}
 
Example 7
Source File: AudioManager.java    From PlayTogether with Apache License 2.0 5 votes vote down vote up
/**
 * 准备录音
 */
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;
	}
}
 
Example 8
Source File: RecordingService.java    From GravityBox with Apache License 2.0 5 votes vote down vote up
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);
    }
}
 
Example 9
Source File: JCameraView.java    From CameraView with Apache License 2.0 5 votes vote down vote up
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();
    }
}
 
Example 10
Source File: Camera2Source.java    From Camera2Vision with Apache License 2.0 5 votes vote down vote up
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());
    }
}
 
Example 11
Source File: RecordingService.java    From AlbumCameraRecorder with MIT License 5 votes vote down vote up
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");
        }
    }
 
Example 12
Source File: Camera2Source.java    From Machine-Learning-Projects-for-Mobile-Applications with MIT License 5 votes vote down vote up
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());
    }
}
 
Example 13
Source File: noxmllayoutexample.java    From ui with Apache License 2.0 5 votes vote down vote up
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();
}
 
Example 14
Source File: QiscusAudioRecorder.java    From qiscus-sdk-android with Apache License 2.0 5 votes vote down vote up
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();
    }
}
 
Example 15
Source File: AudioStream.java    From libstreaming with Apache License 2.0 4 votes vote down vote up
@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;
	
}
 
Example 16
Source File: Camera2.java    From SimpleVideoEditor with Apache License 2.0 4 votes vote down vote up
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;
    }
 
Example 17
Source File: CameraEngine.java    From Fatigue-Detection with MIT License 4 votes vote down vote up
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;
        }
    }
 
Example 18
Source File: DefaultSurfaceRecorder.java    From DeviceConnect-Android with MIT License 4 votes vote down vote up
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);
    }
}
 
Example 19
Source File: WhatsappCameraActivity.java    From WhatsAppCamera with MIT License 4 votes vote down vote up
@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;

}
 
Example 20
Source File: CameraService.java    From glass_snippets with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@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());
	}
}