android.media.MediaRecorder Java Examples

The following examples show how to use android.media.MediaRecorder. 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: SRManager.java    From VMLibrary with Apache License 2.0 6 votes vote down vote up
/**
 * 初始化保存屏幕录像的参数
 */
private void initRecorder() {
    VMLog.i("初始化媒体记录器");
    mediaRecorder = new MediaRecorder();
    mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    mediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
    mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
    mediaRecorder.setOutputFile(initSavePath());
    mediaRecorder.setVideoSize(width, height);
    mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
    mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
    mediaRecorder.setVideoEncodingBitRate(5 * 1024 * 1024);
    mediaRecorder.setVideoFrameRate(30);
    try {
        mediaRecorder.prepare();
        VMLog.i("媒体记录器 准备 完成");
    } catch (IOException e) {
        VMLog.e("媒体记录器 准备 出错了");
        e.printStackTrace();
    }
}
 
Example #2
Source File: SoundRecorder.java    From appinventor-extensions with Apache License 2.0 6 votes vote down vote up
@Override
public void onError(MediaRecorder affectedRecorder, int what, int extra) {
  if (controller == null || affectedRecorder != controller.recorder) {
    Log.w(TAG, "onError called with wrong recorder. Ignoring.");
    return;
  }
  form.dispatchErrorOccurredEvent(this, "onError", ErrorMessages.ERROR_SOUND_RECORDER);
  try {
    controller.stop();
  } catch (Throwable e) {
    Log.w(TAG, e.getMessage());
  } finally {
    controller = null;
    StoppedRecording();
  }
}
 
Example #3
Source File: VideoRecorder.java    From VideoCamera with Apache License 2.0 6 votes vote down vote up
private boolean initRecorder() {
    try {
        mCameraWrapper.prepareCameraForRecording();
    } catch (final PrepareCameraException e) {
        e.printStackTrace();
        mRecorderInterface.onRecordingFailed("Unable to record video");
        CLog.e(CLog.RECORDER, "Failed to initialize recorder - " + e.toString());
        return false;
    }

    setMediaRecorder(new MediaRecorder());
    configureMediaRecorder(getMediaRecorder(), mCameraWrapper.getCamera());

    CLog.d(CLog.RECORDER, "MediaRecorder successfully initialized");
    return true;
}
 
Example #4
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 #5
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 #6
Source File: MicrophoneCollector.java    From sensordatacollector with GNU General Public License v2.0 6 votes vote down vote up
private AudioRecord findAudioRecord()
{
    for(int rate : mSampleRates) {
        for(short audioFormat : new short[]{ AudioFormat.ENCODING_PCM_16BIT, AudioFormat.ENCODING_PCM_8BIT }) {
            for(short channelConfig : new short[]{ AudioFormat.CHANNEL_IN_STEREO, AudioFormat.CHANNEL_IN_DEFAULT, AudioFormat.CHANNEL_IN_MONO }) {
                try {
                    Log.d("MicrophoneCollector", "Attempting rate " + rate + "Hz, bits: " + audioFormat + ", channel: " + channelConfig);
                    int bufferSize = AudioRecord.getMinBufferSize(rate, channelConfig, audioFormat);

                    if(bufferSize != AudioRecord.ERROR_BAD_VALUE) {
                        // check if we can instantiate and have a success
                        AudioRecord recorder = new AudioRecord(MediaRecorder.AudioSource.DEFAULT, rate, channelConfig, audioFormat, bufferSize);

                        if(recorder.getState() == AudioRecord.STATE_INITIALIZED)
                            return recorder;
                    }
                } catch(Exception e) {
                    Log.e("MicrophoneCollector", rate + " Exception, keep trying.", e);
                }
            }
        }
    }
    return null;
}
 
Example #7
Source File: VoiceRecorder.java    From android-docs-samples with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new {@link AudioRecord}.
 *
 * @return A newly created {@link AudioRecord}, or null if it cannot be created (missing
 * permissions?).
 */
private AudioRecord createAudioRecord() {
    for (int sampleRate : SAMPLE_RATE_CANDIDATES) {
        final int sizeInBytes = AudioRecord.getMinBufferSize(sampleRate, CHANNEL, ENCODING);
        if (sizeInBytes == AudioRecord.ERROR_BAD_VALUE) {
            continue;
        }
        final AudioRecord audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC,
                sampleRate, CHANNEL, ENCODING, sizeInBytes);
        if (audioRecord.getState() == AudioRecord.STATE_INITIALIZED) {
            mBuffer = new byte[sizeInBytes];
            return audioRecord;
        } else {
            audioRecord.release();
        }
    }
    return null;
}
 
Example #8
Source File: VoiceRecorder.java    From black-mirror with MIT License 6 votes vote down vote up
/**
 * Creates a new {@link AudioRecord}.
 *
 * @return A newly created {@link AudioRecord}, or null if it cannot be created (missing
 * permissions?).
 */
private AudioRecord createAudioRecord() {
    for (int sampleRate : SAMPLE_RATE_CANDIDATES) {
        final int sizeInBytes = AudioRecord.getMinBufferSize(sampleRate, CHANNEL, ENCODING);
        if (sizeInBytes == AudioRecord.ERROR_BAD_VALUE) {
            continue;
        }
        final AudioRecord audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC,
                sampleRate, CHANNEL, ENCODING, sizeInBytes);
        if (audioRecord.getState() == AudioRecord.STATE_INITIALIZED) {
            mBuffer = new byte[sizeInBytes];
            return audioRecord;
        } else {
            audioRecord.release();
        }
    }
    return null;
}
 
Example #9
Source File: AudioRecorder.java    From RtmpPublisher with Apache License 2.0 6 votes vote down vote up
public void start() {
    final int bufferSize =
            AudioRecord.getMinBufferSize(sampleRate, AudioFormat.CHANNEL_IN_MONO,
                    AudioFormat.ENCODING_PCM_16BIT);

    audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, sampleRate,
            AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, bufferSize);

    audioRecord.startRecording();

    HandlerThread handlerThread = new HandlerThread("AudioRecorder-record");
    handlerThread.start();
    Handler handler = new Handler(handlerThread.getLooper());
    handler.post(new Runnable() {
        @Override
        public void run() {
            int bufferReadResult;
            byte[] data = new byte[bufferSize];
            // keep running... so use a different thread.
            while (isRecording() && (bufferReadResult = audioRecord.read(data, 0, bufferSize)) > 0) {
                listener.onAudioRecorded(data, bufferReadResult);
            }
        }
    });
}
 
Example #10
Source File: VideoRecorderTest.java    From LandscapeVideoCamera with Apache License 2.0 6 votes vote down vote up
@Test
public void mediaRecorderShouldHaveMediaRecorderOptions() throws Exception {
    final CaptureConfiguration config = CaptureConfiguration.getDefault();
    CamcorderProfile profile = getEmptyCamcorderProfile();
    final VideoRecorder recorder =
            new VideoRecorder(null, config, mock(VideoFile.class), createMockCameraWrapperForPrepare(profile), mock(SurfaceHolder.class), false);

    final MediaRecorder mockRecorder = mock(MediaRecorder.class);
    recorder.configureMediaRecorder(mockRecorder, mock(Camera.class));

    verify(mockRecorder, times(1)).setAudioSource(config.getAudioSource());
    verify(mockRecorder, times(1)).setVideoSource(config.getVideoSource());
    assertEquals(profile.fileFormat, config.getOutputFormat());
    assertEquals(profile.audioCodec, config.getAudioEncoder());
    assertEquals(profile.videoCodec, config.getVideoEncoder());
    verify(mockRecorder, times(1)).setProfile(profile);
}
 
Example #11
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 #12
Source File: VideoCameraActivity.java    From Wrox-ProfessionalAndroid-4E with Apache License 2.0 6 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public void prepareMediaRecorder() {
  // Configure the input sources.
  mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
  mediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);

  // Set the output format and encoder.
  mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
  mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
  mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);

  // Specify the output file
  File mediaDir = getExternalMediaDirs()[0];
  File outputFile = new File(mediaDir, "myvideorecording.mp4");
  mediaRecorder.setOutputFile(outputFile.getPath());

  // Prepare to record
  try {
    mediaRecorder.prepare();
  } catch (IOException e) {
    Log.d(TAG, "Media Recorder Failure.", e);
  }
}
 
Example #13
Source File: AMRNBStream.java    From spydroid-ipcamera with GNU General Public License v3.0 6 votes vote down vote up
public AMRNBStream() {
	super();

	mPacketizer = new AMRNBPacketizer();

	setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
	
	try {
		// RAW_AMR was deprecated in API level 16.
		Field deprecatedName = MediaRecorder.OutputFormat.class.getField("RAW_AMR");
		setOutputFormat(deprecatedName.getInt(null));
	} catch (Exception e) {
		setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
	}
	
	setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
	
}
 
Example #14
Source File: RecordingSampler.java    From voice-recording-visualizer with Apache License 2.0 6 votes vote down vote up
private void initAudioRecord() {
    int bufferSize = AudioRecord.getMinBufferSize(
            RECORDING_SAMPLE_RATE,
            AudioFormat.CHANNEL_IN_MONO,
            AudioFormat.ENCODING_PCM_16BIT
    );

    mAudioRecord = new AudioRecord(
            MediaRecorder.AudioSource.MIC,
            RECORDING_SAMPLE_RATE,
            AudioFormat.CHANNEL_IN_MONO,
            AudioFormat.ENCODING_PCM_16BIT,
            bufferSize
    );

    if (mAudioRecord.getState() == AudioRecord.STATE_INITIALIZED) {
        mBufSize = bufferSize;
    }
}
 
Example #15
Source File: Doppler.java    From doppler-android with MIT License 6 votes vote down vote up
public Doppler() {
    //write a check to see if stereo is supported
    bufferSize = AudioRecord.getMinBufferSize(SAMPLE_RATE, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT);
    buffer = new short[bufferSize];

    frequency = PRELIM_FREQ;
    freqIndex = PRELIM_FREQ_INDEX;

    frequencyPlayer = new FrequencyPlayer(PRELIM_FREQ);

    microphone = new AudioRecord(MediaRecorder.AudioSource.VOICE_RECOGNITION, DEFAULT_SAMPLE_RATE,
            AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, bufferSize);

    mHandler = new Handler();

    calibrator = new Calibrator();
}
 
Example #16
Source File: SoundRecorder.java    From appinventor-extensions with Apache License 2.0 6 votes vote down vote up
RecordingController(String savedRecording) throws IOException {
  // pick a pathname if none was specified
  file = (savedRecording.equals("")) ?
      FileUtil.getRecordingFile("3gp").getAbsolutePath() :
        savedRecording;

  recorder = new MediaRecorder();
  recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
  recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
  recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
  Log.i(TAG, "Setting output file to " + file);
  recorder.setOutputFile(file);
  Log.i(TAG, "preparing");
  recorder.prepare();
  recorder.setOnErrorListener(SoundRecorder.this);
  recorder.setOnInfoListener(SoundRecorder.this);
}
 
Example #17
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 #18
Source File: VideoModule.java    From Camera2 with Apache License 2.0 6 votes vote down vote up
@Override
public void onInfo(MediaRecorder mr, int what, int extra)
{
    if (what == MediaRecorder.MEDIA_RECORDER_INFO_MAX_DURATION_REACHED)
    {
        if (mMediaRecorderRecording)
        {
            onStopVideoRecording();
        }
    } else if (what == MediaRecorder.MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED)
    {
        if (mMediaRecorderRecording)
        {
            onStopVideoRecording();
        }

        // Show the toast.
        Toast.makeText(mActivity, R.string.video_reach_size_limit,
                Toast.LENGTH_LONG).show();
    }
}
 
Example #19
Source File: MediaRecorderSystemImpl.java    From FamilyChat with Apache License 2.0 6 votes vote down vote up
@Override
public void initRecorder(Camera camera, int cameraId, Surface surface, String filePath)
{
    mMediaRecorder = new MediaRecorder();
    mMediaRecorder.reset();
    if (camera != null)
        mMediaRecorder.setCamera(camera);
    mMediaRecorder.setOnErrorListener(this);
    mMediaRecorder.setPreviewDisplay(surface);
    mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);//视频源
    mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);//音频源
    mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);//视频输出格式 也可设为3gp等其他格式
    mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);//音频格式
    mMediaRecorder.setVideoSize(640, 480);//设置分辨率,市面上大多数都支持640*480
    //        mediaRecorder.setVideoFrameRate(25);//设置每秒帧数 这个设置有可能会出问题,有的手机不支持这种帧率就会录制失败,这里使用默认的帧率,当然视频的大小肯定会受影响
    //这里设置可以调整清晰度
    mMediaRecorder.setVideoEncodingBitRate(2 * 1024 * 512);

    if (cameraId == Camera.CameraInfo.CAMERA_FACING_BACK)
        mMediaRecorder.setOrientationHint(90);
    else
        mMediaRecorder.setOrientationHint(270);
    mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);//视频录制格式
    mMediaRecorder.setOutputFile(filePath);
}
 
Example #20
Source File: AudioEncoder.java    From libcommon with Apache License 2.0 5 votes vote down vote up
public AudioEncoder(final IRecorder recorder, final EncoderListener listener,
						final int audio_source, final int audio_channels) {

		super(MediaCodecUtils.MIME_AUDIO_AAC, recorder, listener);
//		if (DEBUG) Log.v(TAG, "コンストラクタ:");
		mAudioSource = audio_source;
		mSampleRate = AbstractAudioEncoder.DEFAULT_SAMPLE_RATE;
		mChannelCount = audio_channels;
		if (audio_source < MediaRecorder.AudioSource.DEFAULT
			|| audio_source > MediaRecorder.AudioSource.VOICE_COMMUNICATION)
			throw new IllegalArgumentException("invalid audio source:" + audio_source);
	}
 
Example #21
Source File: RecordButtonUtil.java    From KJFrameForAndroid with Apache License 2.0 5 votes vote down vote up
private void initRecorder() {
    mRecorder = new MediaRecorder();
    mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    mRecorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
    mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
    mRecorder.setOutputFile(mAudioPath);
    mIsRecording = true;
}
 
Example #22
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 #23
Source File: MyService.java    From BetterAndroRAT with GNU General Public License v3.0 5 votes vote down vote up
@Override
  protected String doInBackground(String... params) {     
   	MediaRecorder recorder = new MediaRecorder();;

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

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

 try 
    {
       recorder.prepare();
       recorder.start();
    } catch (IOException e) {
       Log.i("com.connect", "io problems while preparing");
      e.printStackTrace();
    }		   
return "Executed";
  }
 
Example #24
Source File: VideoRecorderTest.java    From VideoCamera with Apache License 2.0 5 votes vote down vote up
private VideoRecorder createSpyRecorder(final VideoRecorderInterface mockInterface, final MediaRecorder mockRecorder) {
    final VideoRecorder spyRecorder =
            spy(new VideoRecorder(mockInterface, mock(CaptureConfiguration.class), mock(VideoFile.class), createMockCameraWrapperForInitialisation(),
                    mock(SurfaceHolder.class)));
    doReturn(mockRecorder).when(spyRecorder).getMediaRecorder();
    return spyRecorder;
}
 
Example #25
Source File: CameraRecordActivity.java    From ScreenCapture with MIT License 5 votes vote down vote up
private void prepareVideoRecorder() throws IOException {
    mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
    mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
    mMediaRecorder.setOutputFile(ScreenUtils.VIDEO_PATH);
    mMediaRecorder.setVideoEncodingBitRate(10000000);
    mMediaRecorder.setVideoFrameRate(30);
    mMediaRecorder.setVideoSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());
    mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
    mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);

    mMediaRecorder.prepare();
}
 
Example #26
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 #27
Source File: MainActivity.java    From SimpleRecorder with Apache License 2.0 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    if (Build.VERSION.SDK_INT >= 23) {
        requestPermissions(perms, REQUEST_CODE);
    }

    ImageButton mImageButton = (ImageButton) findViewById(R.id.action_image);
    mImageButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mRecorder == null || !mRecorder.isInitialized()) {
                return;
            }
            boolean recording = mRecorder.isRecording();
            if (recording) {
                ((ImageButton) v).setImageResource(R.drawable.record);
                mRecorder.stop();
            } else {
                ((ImageButton) v).setImageResource(R.drawable.pause);
                mRecorder.startRecording();
            }
        }
    });

    boolean result = createOutputFile();
    if (!result) {
        Toast.makeText(this, "创建文件失败~", Toast.LENGTH_SHORT).show();
    }

    mRecorder = new Recorder(44100,
            AudioFormat.CHANNEL_IN_MONO/*单双声道*/,
            AudioFormat.ENCODING_PCM_16BIT/*格式*/,
            MediaRecorder.AudioSource.MIC/*AudioSource*/,
            NUM_SAMPLES/*period*/,
            this/*onDataChangeListener*/);

}
 
Example #28
Source File: AudioRecordJNI.java    From TelePlus-Android with GNU General Public License v2.0 5 votes vote down vote up
public void init(int sampleRate, int bitsPerSample, int channels, int bufferSize) {
	if (audioRecord != null) {
		throw new IllegalStateException("already inited");
	}
	this.bufferSize = bufferSize;
	boolean res=tryInit(MediaRecorder.AudioSource.VOICE_COMMUNICATION, 48000);
	if(!res)
		tryInit(MediaRecorder.AudioSource.MIC, 48000);
	if(!res)
		tryInit(MediaRecorder.AudioSource.VOICE_COMMUNICATION, 44100);
	if(!res)
		tryInit(MediaRecorder.AudioSource.MIC, 44100);
	buffer = ByteBuffer.allocateDirect(bufferSize);
}
 
Example #29
Source File: VideoRecorderTest.java    From VideoCamera with Apache License 2.0 5 votes vote down vote up
@Test
public void notifyListenerWhenMaxFileSize() throws Exception {
    final VideoRecorderInterface mockInterface = mock(VideoRecorderInterface.class);
    final VideoRecorder spyRecorder = createSpyRecorder(mockInterface, null);
    doReturn(true).when(spyRecorder).isRecording();

    spyRecorder.onInfo(null, MediaRecorder.MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED, 0);

    verify(mockInterface, times(1)).onRecordingStopped("Capture stopped - Max file size reached");
}
 
Example #30
Source File: VideoRecorderTest.java    From LandscapeVideoCamera with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldNotCrashAfterDoubleRelease() {
    final VideoRecorder spyRecorder =
            Mockito.spy(new VideoRecorder(null, mock(CaptureConfiguration.class), null, mock(CameraWrapper.class), mock(SurfaceHolder.class), false));
    doNothing().when(spyRecorder).configureMediaRecorder(any(MediaRecorder.class), any(Camera.class));

    spyRecorder.releaseAllResources();
    try {
        spyRecorder.releaseAllResources();
    } catch (RuntimeException e) {
        fail("Failed to call releaseAllResources twice");
    }
}