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

The following examples show how to use android.media.MediaRecorder#setAudioChannels() . 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: RecordingService.java    From SoundRecorder with GNU General Public License v3.0 6 votes vote down vote up
public void startRecording() {
    setFileNameAndPath();

    mRecorder = new MediaRecorder();
    mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    mRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
    mRecorder.setOutputFile(mFilePath);
    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 2
Source File: AudioRecorder.java    From zom-android-matrix with Apache License 2.0 5 votes vote down vote up
public void startAudioRecording() {
    AudioManager am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
    if (am.getMode() == AudioManager.MODE_NORMAL) {

        mediaRecorder = new MediaRecorder();

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

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

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

        mediaRecorder.setOutputFile(outputFilePath.getAbsolutePath());

        try {
            isAudioRecording = true;
            mediaRecorder.prepare();
            mediaRecorder.start();

            if (getVisualizerView() != null) {
                startLevelListener();
            }
        } catch (Exception e) {
            Log.e(LOG_TAG, "couldn't start audio", e);
        }
    }
}
 
Example 3
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 4
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 5
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 6
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 7
Source File: AudioStream.java    From spydroid-ipcamera with GNU General Public License v3.0 5 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 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 !");
	}
	
}
 
Example 8
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 9
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 10
Source File: CameraEngine.java    From In77Camera 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 11
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 12
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 13
Source File: ConversationDetailActivity.java    From Zom-Android-XMPP with GNU General Public License v3.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(ImApp.LOG_TAG, "couldn't start audio", e);
            }
        }
    }
}
 
Example 14
Source File: VideoOverlay.java    From backgroundvideo with GNU General Public License v3.0 4 votes vote down vote up
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;
    }
}
 
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: AACStream.java    From libstreaming with Apache License 2.0 4 votes vote down vote up
/** 
 * 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");

}