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

The following examples show how to use android.media.MediaRecorder#start() . 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: CaptureVideoActivity.java    From NIM_Android_UIKit with MIT License 6 votes vote down vote up
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;
}
 
Example 2
Source File: AudioRecordingActivity.java    From coursera-android with MIT License 6 votes vote down vote up
private void startRecording() {

        mRecorder = new MediaRecorder();
        mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        mRecorder.setOutputFile(mFileName);
        mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

        try {
            mRecorder.prepare();
        } catch (IOException e) {
            Log.e(TAG, "Couldn't prepare and start MediaRecorder");
        }

        mRecorder.start();
    }
 
Example 3
Source File: TestActivity.java    From BluetoothCameraAndroid with MIT License 6 votes vote down vote up
protected void startRecording() throws IOException {
    mMediaRecorder = new MediaRecorder();  // Works well
    mCamera.unlock();

    mMediaRecorder.setCamera(mCamera);

    mMediaRecorder.setPreviewDisplay(mSurfaceHolder.getSurface());
    mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
    mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);

    mMediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));
    mMediaRecorder.setOutputFile("/sdcard/zzzz.mp4");

    mMediaRecorder.prepare();
    mMediaRecorder.start();
}
 
Example 4
Source File: RecorderActivity.java    From droid-stealth with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Starts the media recorder to record a new fragment
 */
private void startRecording() {
	mRecorder = new MediaRecorder();
	mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
	mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
	mRecorder.setOutputFile(FileUtils.getPath(this, mOutputUri));
	mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
	try {
		mRecorder.prepare();
	}
	catch (IOException e) {
		Utils.d("Error writing file: "+e.toString());
		Toast.makeText(getApplicationContext(), "An error occured at recorder preparations.", Toast.LENGTH_LONG)
				.show();
	}

	mRecorder.start();
	mVolumeChecker.run();
}
 
Example 5
Source File: RecordingActivity.java    From Conversations with GNU General Public License v3.0 6 votes vote down vote up
private boolean startRecording() {
    mRecorder = new MediaRecorder();
    mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    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 6
Source File: AudioRecordingActivity.java    From coursera-android with MIT License 6 votes vote down vote up
private void startRecording() {

		mRecorder = new MediaRecorder();
		mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
		mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
		mRecorder.setOutputFile(mFileName);
		mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

		try {
			mRecorder.prepare();
		} catch (IOException e) {
			Log.e(TAG, "Couldn't prepare and start MediaRecorder");
		}

		mRecorder.start();
	}
 
Example 7
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 8
Source File: noxmllayoutexample.java    From ui with Apache License 2.0 5 votes vote down vote up
private void startRecording() {
    mRecorder = new MediaRecorder();
    mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
    mRecorder.setOutputFile(mFileName);
    mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

    try {
        mRecorder.prepare();
    } catch (IOException e) {
        Log.e(LOG_TAG, "prepare() failed");
    }

    mRecorder.start();
}
 
Example 9
Source File: AudioNoteActivity.java    From privacy-friendly-notes with GNU General Public License v3.0 5 votes vote down vote up
private void startRecording() {
    recording = true;
    mRecorder = new MediaRecorder();
    mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    mRecorder.setOutputFormat(MediaRecorder.OutputFormat.AAC_ADTS);
    mRecorder.setOutputFile(mFilePath);
    mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
    try {
        mRecorder.prepare();
        final Animation animation = new AlphaAnimation(1, (float)0.5); // Change alpha from fully visible to invisible
        animation.setDuration(500); // duration - half a second
        animation.setInterpolator(new LinearInterpolator()); // do not alter animation rate
        animation.setRepeatCount(Animation.INFINITE); // Repeat animation infinitely
        animation.setRepeatMode(Animation.REVERSE); // Reverse animation at the end so the button will fade back in
        btnRecord.startAnimation(animation);
        startTime = System.currentTimeMillis();
        AudioNoteActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (mRecorder != null) {
                    long time = System.currentTimeMillis() - startTime;
                    int seconds = (int) time / 1000;
                    int minutes = seconds / 60;
                    seconds = seconds % 60;
                    tvRecordingTime.setText(String.format("%02d", minutes) + ":" + String.format("%02d", seconds));
                    mHandler.postDelayed(this, 100);
                }
            }
        });

        mRecorder.start();
    } catch (IOException e) {
        recording = false;
        e.printStackTrace();
    }
}
 
Example 10
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 11
Source File: MainActivity.java    From AndroidVoiceAnimation with Apache License 2.0 5 votes vote down vote up
@Override
public void onRecordStart() {
    Log.d(TAG, "onRecordStart");
    try {
        mMediaRecorder = new MediaRecorder();
        mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
        mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        mMediaRecorder.setOutputFile(new File(Environment.getExternalStorageDirectory(), "audio.amr").getAbsolutePath());
        mMediaRecorder.prepare();
        mMediaRecorder.start();
        mIsRecording = true;
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                float radius = (float) Math.log10(Math.max(1, mMediaRecorder.getMaxAmplitude() - 500)) * ScreenUtils.dp2px(MainActivity.this, 20);
                mTextView.setText(String.valueOf(radius));
                mVoiceView.animateRadius(radius);
                if (mIsRecording) {
                    mHandler.postDelayed(this, 50);
                }
            }
        });
    } catch (IOException e) {
        Toast.makeText(this, "MediaRecorder prepare failed!", Toast.LENGTH_SHORT).show();
        e.printStackTrace();
    }
}
 
Example 12
Source File: HostAudioRecorder.java    From DeviceConnect-Android with MIT License 5 votes vote down vote up
private void initAudioContext(final String fileName, final RecordingListener listener) throws IOException {
    FileManager fileMgr = new FileManager(mContext, HostFileProvider.class.getName());
    mFile = new File(fileMgr.getBasePath(), fileName);

    mMediaRecorder = new MediaRecorder();
    mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
    mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
    mMediaRecorder.setOutputFile(mFile.toString());
    mMediaRecorder.prepare();
    mMediaRecorder.start();
}
 
Example 13
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 14
Source File: AudioRecorder.java    From PrivacyStreams with Apache License 2.0 5 votes vote down vote up
static Audio recordAudio(UQI uqi, long duration) throws IOException {
    List<Integer> amplitudes = new ArrayList<>();

    MediaRecorder recorder = new MediaRecorder();
    recorder.setAudioSource(Globals.AudioConfig.audioSource);
    recorder.setOutputFormat(Globals.AudioConfig.outputFormat);
    recorder.setAudioEncoder(Globals.AudioConfig.audioEncoder);

    String audioPath = "temp/audio_" + TimeUtils.getTimeTag() + ".amr";
    File tempAudioFile = StorageUtils.getValidFile(uqi.getContext(), audioPath, false);
    recorder.setOutputFile(tempAudioFile.getAbsolutePath());

    recorder.prepare();
    recorder.start();   // Recording is now started

    long startTime = System.currentTimeMillis();
    while (true) {
        long currentTime = System.currentTimeMillis();
        if (currentTime - startTime > duration) {
            break;
        }
        amplitudes.add(recorder.getMaxAmplitude());
    }

    recorder.stop();
    recorder.reset();   // You can reuse the object by going back to setAudioSource() step
    recorder.release(); // Now the object cannot be reused

    AudioData audioData = AudioData.newTempRecord(tempAudioFile, amplitudes);

    return new Audio(startTime, audioData);
}
 
Example 15
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 16
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 17
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 18
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");

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