下面列出了android.media.MediaRecorder#setAudioSource ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public void startRecording(Camera.PreviewCallback previewCallback) {
recording = true;
mCamera.unlock();
mRecordbutton.setBackgroundResource(R.drawable.red_circle_background);
mMediaRecorder = new MediaRecorder();
mMediaRecorder.setCamera(mCamera);
mMediaRecorder.setPreviewDisplay(mSurfaceHolder.getSurface());
mMediaRecorder.setOutputFile("/sdcard/Video.mp4");
mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
mMediaRecorder.setOrientationHint(90);
mMediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));
try {
mMediaRecorder.prepare();
mMediaRecorder.start();
mCamera.startPreview();
mCamera.setPreviewCallback(previewCallback);
} catch (IOException e) {
e.printStackTrace();
}
}
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(TAG, "Couldn't prepare and start MediaRecorder");
}
mRecorder.start();
}
/**
* 動画撮影のための準備を行います.
*
* @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();
}
private boolean startRecorderInternal() throws Exception {
shutdownCamera();
if (!initCamera()) {
return false;
}
switchCamera.setVisibility(View.GONE);
mediaRecorder = new MediaRecorder();
camera.unlock();
mediaRecorder.setCamera(camera);
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
setCamcorderProfile();
mediaRecorder.setPreviewDisplay(surfaceHolder.getSurface());
mediaRecorder.setMaxDuration(1000 * VIDEO_TIMES);
mediaRecorder.setOutputFile(filename);
setVideoOrientation();
mediaRecorder.prepare();
mediaRecorder.start();
return true;
}
/**
* 准备录音
*/
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;
}
}
@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 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();
}
/**
* 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);
}
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 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);
}
}
@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());
recorder.setVideoFrameRate(mCaptureConfiguration.getVideoFPS());
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);
}
@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 ouput 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
mMediaRecorder.setOutputFile(mSender.getFileDescriptor());
mMediaRecorder.prepare();
mMediaRecorder.start();
try {
// mReceiver.getInputStream contains the data from the camera
// the mPacketizer encapsulates this stream in an RTP stream and send it over the network
mPacketizer.setDestination(mDestination, mRtpPort, mRtcpPort);
mPacketizer.setInputStream(mReceiver.getInputStream());
mPacketizer.start();
mStreaming = true;
} catch (IOException e) {
stop();
throw new IOException("Something happened with the local sockets :/ Start failed !");
}
}
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;
}
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);
}
}
public void startRecord(final String filePath, final String camera, final int width, final int height, final int quality, final boolean withFlash){
Log.d(TAG, "CameraPreview startRecord camera: " + camera + " width: " + width + ", height: " + height + ", quality: " + quality);
Activity activity = getActivity();
muteStream(true, activity);
if (this.mRecordingState == RecordingState.STARTED) {
Log.d(TAG, "Already Recording");
return;
}
this.recordFilePath = filePath;
int mOrientationHint = calculateOrientationHint();
int videoWidth = 0;//set whatever
int videoHeight = 0;//set whatever
Camera.Parameters cameraParams = mCamera.getParameters();
if (withFlash) {
cameraParams.setFlashMode(withFlash ? Camera.Parameters.FLASH_MODE_TORCH : Camera.Parameters.FLASH_MODE_OFF);
mCamera.setParameters(cameraParams);
mCamera.startPreview();
}
mCamera.unlock();
mRecorder = new MediaRecorder();
try {
mRecorder.setCamera(mCamera);
CamcorderProfile profile;
if (CamcorderProfile.hasProfile(defaultCameraId, CamcorderProfile.QUALITY_HIGH)) {
profile = CamcorderProfile.get(defaultCameraId, CamcorderProfile.QUALITY_HIGH);
} else {
if (CamcorderProfile.hasProfile(defaultCameraId, CamcorderProfile.QUALITY_480P)) {
profile = CamcorderProfile.get(defaultCameraId, CamcorderProfile.QUALITY_480P);
} else {
if (CamcorderProfile.hasProfile(defaultCameraId, CamcorderProfile.QUALITY_720P)) {
profile = CamcorderProfile.get(defaultCameraId, CamcorderProfile.QUALITY_720P);
} else {
if (CamcorderProfile.hasProfile(defaultCameraId, CamcorderProfile.QUALITY_1080P)) {
profile = CamcorderProfile.get(defaultCameraId, CamcorderProfile.QUALITY_1080P);
} else {
profile = CamcorderProfile.get(defaultCameraId, CamcorderProfile.QUALITY_LOW);
}
}
}
}
mRecorder.setAudioSource(MediaRecorder.AudioSource.VOICE_RECOGNITION);
mRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
mRecorder.setProfile(profile);
mRecorder.setOutputFile(filePath);
mRecorder.setOrientationHint(mOrientationHint);
mRecorder.prepare();
Log.d(TAG, "Starting recording");
mRecorder.start();
eventListener.onStartRecordVideo();
} catch (IOException e) {
eventListener.onStartRecordVideoError(e.getMessage());
}
}
public void Start(String filePath) throws Exception {
if (this.mRecordingState == RecordingState.STARTED) {
Log.w(TAG, "Already Recording");
return;
}
if (!TextUtils.isEmpty(filePath)) {
this.mFilePath = filePath;
}
attachView();
if (this.mRecordingState == RecordingState.INITIALIZING) {
this.mStartWhenInitialized = true;
return;
}
if (TextUtils.isEmpty(mFilePath)) {
throw new IllegalArgumentException("Filename for recording must be set");
}
initializeCamera();
if (mCamera == null) {
this.detachView();
throw new NullPointerException("Cannot start recording, we don't have a camera!");
}
// Set camera parameters
Camera.Parameters cameraParameters = mCamera.getParameters();
mCamera.stopPreview(); //Apparently helps with freezing issue on some Samsung devices.
mCamera.unlock();
try {
mRecorder = new MediaRecorder();
mRecorder.setCamera(mCamera);
CamcorderProfile profile;
if (CamcorderProfile.hasProfile(mCameraId, CamcorderProfile.QUALITY_LOW)) {
profile = CamcorderProfile.get(mCameraId, CamcorderProfile.QUALITY_LOW);
} else {
profile = CamcorderProfile.get(mCameraId, CamcorderProfile.QUALITY_HIGH);
}
Camera.Size lowestRes = CameraHelper.getLowestResolution(cameraParameters);
profile.videoFrameWidth = lowestRes.width;
profile.videoFrameHeight = lowestRes.height;
mRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
if (mRecordAudio) {
// With audio
mRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mRecorder.setVideoFrameRate(profile.videoFrameRate);
mRecorder.setVideoSize(profile.videoFrameWidth, profile.videoFrameHeight);
mRecorder.setVideoEncodingBitRate(profile.videoBitRate);
mRecorder.setAudioEncodingBitRate(profile.audioBitRate);
mRecorder.setAudioChannels(profile.audioChannels);
mRecorder.setAudioSamplingRate(profile.audioSampleRate);
mRecorder.setVideoEncoder(profile.videoCodec);
mRecorder.setAudioEncoder(profile.audioCodec);
} else {
// Without audio
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mRecorder.setVideoFrameRate(profile.videoFrameRate);
mRecorder.setVideoSize(profile.videoFrameWidth, profile.videoFrameHeight);
mRecorder.setVideoEncodingBitRate(profile.videoBitRate);
mRecorder.setVideoEncoder(profile.videoCodec);
}
mRecorder.setOutputFile(filePath);
mRecorder.setOrientationHint(mOrientation);
mRecorder.prepare();
Log.d(TAG, "Starting recording");
mRecorder.start();
} catch (Exception e) {
this.releaseCamera();
Log.e(TAG, "Could not start recording! MediaRecorder Error", e);
throw e;
}
}
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);
}
}
/**
* Records a short sample of AAC ADTS from the microphone to find out what the sampling rate really is
* On some phone indeed, no error will be reported if the sampling rate used differs from the
* one selected with setAudioSamplingRate
* @throws IOException
* @throws IllegalStateException
*/
@SuppressLint("InlinedApi")
private void testADTS() throws IllegalStateException, IOException {
setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
try {
Field name = MediaRecorder.OutputFormat.class.getField("AAC_ADTS");
setOutputFormat(name.getInt(null));
}
catch (Exception ignore) {
setOutputFormat(6);
}
String key = PREF_PREFIX+"aac-"+mQuality.samplingRate;
if (mSettings!=null && mSettings.contains(key)) {
String[] s = mSettings.getString(key, "").split(",");
mQuality.samplingRate = Integer.valueOf(s[0]);
mConfig = Integer.valueOf(s[1]);
mChannel = Integer.valueOf(s[2]);
return;
}
final String TESTFILE = Environment.getExternalStorageDirectory().getPath()+"/spydroid-test.adts";
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
throw new IllegalStateException("No external storage or external storage not ready !");
}
// The structure of an ADTS packet is described here: http://wiki.multimedia.cx/index.php?title=ADTS
// ADTS header is 7 or 9 bytes long
byte[] buffer = new byte[9];
mMediaRecorder = new MediaRecorder();
mMediaRecorder.setAudioSource(mAudioSource);
mMediaRecorder.setOutputFormat(mOutputFormat);
mMediaRecorder.setAudioEncoder(mAudioEncoder);
mMediaRecorder.setAudioChannels(1);
mMediaRecorder.setAudioSamplingRate(mQuality.samplingRate);
mMediaRecorder.setAudioEncodingBitRate(mQuality.bitRate);
mMediaRecorder.setOutputFile(TESTFILE);
mMediaRecorder.setMaxDuration(1000);
mMediaRecorder.prepare();
mMediaRecorder.start();
// We record for 1 sec
// TODO: use the MediaRecorder.OnInfoListener
try {
Thread.sleep(2000);
} catch (InterruptedException e) {}
mMediaRecorder.stop();
mMediaRecorder.release();
mMediaRecorder = null;
File file = new File(TESTFILE);
RandomAccessFile raf = new RandomAccessFile(file, "r");
// ADTS packets start with a sync word: 12bits set to 1
while (true) {
if ( (raf.readByte()&0xFF) == 0xFF ) {
buffer[0] = raf.readByte();
if ( (buffer[0]&0xF0) == 0xF0) break;
}
}
raf.read(buffer,1,5);
mSamplingRateIndex = (buffer[1]&0x3C)>>2 ;
mProfile = ( (buffer[1]&0xC0) >> 6 ) + 1 ;
mChannel = (buffer[1]&0x01) << 2 | (buffer[2]&0xC0) >> 6 ;
mQuality.samplingRate = AUDIO_SAMPLING_RATES[mSamplingRateIndex];
// 5 bits for the object type / 4 bits for the sampling rate / 4 bits for the channel / padding
mConfig = (mProfile & 0x1F) << 11 | (mSamplingRateIndex & 0x0F) << 7 | (mChannel & 0x0F) << 3;
Log.i(TAG,"MPEG VERSION: " + ( (buffer[0]&0x08) >> 3 ) );
Log.i(TAG,"PROTECTION: " + (buffer[0]&0x01) );
Log.i(TAG,"PROFILE: " + AUDIO_OBJECT_TYPES[ mProfile ] );
Log.i(TAG,"SAMPLING FREQUENCY: " + mQuality.samplingRate );
Log.i(TAG,"CHANNEL: " + mChannel );
raf.close();
if (mSettings!=null) {
Editor editor = mSettings.edit();
editor.putString(key, mQuality.samplingRate+","+mConfig+","+mChannel);
editor.commit();
}
if (!file.delete()) Log.e(TAG,"Temp file could not be erased");
}
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;
}
}