Java Code Examples for android.media.AudioRecord#getMinBufferSize()

The following examples show how to use android.media.AudioRecord#getMinBufferSize() . 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: 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 2
Source File: MicrophoneSource.java    From media-for-mobile with Apache License 2.0 6 votes vote down vote up
public synchronized void configure(int sampleRate, int channels) {
    this.sampleRate = sampleRate;
    recordChannels = channels;

    switch (recordChannels) {
        case 1: {
            androidChannels = AudioFormat.CHANNEL_IN_MONO;
        }
        break;

        case 2: {
            androidChannels = AudioFormat.CHANNEL_IN_STEREO;
        }
        break;
    }

    minBufferSize = AudioRecord.getMinBufferSize(sampleRate, androidChannels, audioEncoding);

    if (minBufferSize < 0) {
        this.sampleRate = 8000;
        minBufferSize = AudioRecord.getMinBufferSize(sampleRate, androidChannels, audioEncoding);
    }
}
 
Example 3
Source File: AudioDispatcherFactory.java    From cythara with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Create a new AudioDispatcher connected to the default microphone.
 * 
 * @param sampleRate
 *            The requested sample rate.
 * @param audioBufferSize
 *            The size of the audio buffer (in samples).
 * 
 * @param bufferOverlap
 *            The size of the overlap (in samples).
 * @return A new AudioDispatcher
 */
public static AudioDispatcher fromDefaultMicrophone(final int sampleRate,
		final int audioBufferSize, final int bufferOverlap) {
	int minAudioBufferSize = AudioRecord.getMinBufferSize(sampleRate,
			android.media.AudioFormat.CHANNEL_IN_MONO,
			android.media.AudioFormat.ENCODING_PCM_16BIT);
	int minAudioBufferSizeInSamples =  minAudioBufferSize/2;
	if(minAudioBufferSizeInSamples <= audioBufferSize ){
	AudioRecord audioInputStream = new AudioRecord(
			MediaRecorder.AudioSource.MIC, sampleRate,
			android.media.AudioFormat.CHANNEL_IN_MONO,
			android.media.AudioFormat.ENCODING_PCM_16BIT,
			audioBufferSize * 2);

	TarsosDSPAudioFormat format = new TarsosDSPAudioFormat(sampleRate, 16,1, true, false);
	
	TarsosDSPAudioInputStream audioStream = new AndroidAudioInputStream(audioInputStream, format);
	//start recording ! Opens the stream.
	audioInputStream.startRecording();
	return new AudioDispatcher(audioStream,audioBufferSize,bufferOverlap);
	}else{
		throw new IllegalArgumentException("Buffer size too small should be at least " + (minAudioBufferSize *2));
	}
}
 
Example 4
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 5
Source File: SpeaktoitRecognitionServiceImpl.java    From dialogflow-android-client with Apache License 2.0 6 votes vote down vote up
private void init() {
    synchronized (recognizerLock) {
        final int bufferSize = AudioRecord.getMinBufferSize(SAMPLE_RATE_IN_HZ, CHANNEL_CONFIG, AUDIO_FORMAT);

        audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC,
                SAMPLE_RATE_IN_HZ,
                CHANNEL_CONFIG,
                AUDIO_FORMAT,
                bufferSize);

        vad.setEnabled(config.isVoiceActivityDetectionEnabled());
        vad.setSpeechListener(this);

        mediaPlayer = new MediaPlayer();
        mediaPlayer.setOnErrorListener(this);
        mediaPlayer.setOnCompletionListener(this);
    }
}
 
Example 6
Source File: PcmToWavUtil.java    From PhotoMovie with Apache License 2.0 5 votes vote down vote up
/**
 * @param sampleRate sample rate、采样率
 * @param channelConfig    channel、声道
 * @param encoding   Audio data format、音频格式
 */
public PcmToWavUtil(int sampleRate, int channelConfig, int channelCount, int encoding) {
    this.mSampleRate = sampleRate;
    this.mChannelConfig = channelConfig;
    this.mChannelCount = channelCount;
    this.mEncoding = encoding;
    this.mBufferSize = AudioRecord.getMinBufferSize(mSampleRate, mChannelConfig, mEncoding);
}
 
Example 7
Source File: AudioManagerAndroid.java    From android-chromium with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
* Returns the minimum frame size required for audio input.
*
* @param sampleRate sampling rate
* @param channels number of channels
*/
 @CalledByNative
 private static int getMinInputFrameSize(int sampleRate, int channels) {
     int channelConfig;
     if (channels == 1) {
         channelConfig = AudioFormat.CHANNEL_IN_MONO;
     } else if (channels == 2) {
         channelConfig = AudioFormat.CHANNEL_IN_STEREO;
     } else {
         return -1;
     }
     return AudioRecord.getMinBufferSize(
             sampleRate, channelConfig, AudioFormat.ENCODING_PCM_16BIT) / 2 / channels;
 }
 
Example 8
Source File: AudioRecordThread.java    From dcs-sdk-java with Apache License 2.0 5 votes vote down vote up
public AudioRecordThread(LinkedBlockingDeque<byte[]> linkedBlockingDeque) {
    this.linkedBlockingDeque = linkedBlockingDeque;
    bufferSize = AudioRecord.getMinBufferSize(SAMPLE_RATE_HZ, AudioFormat.CHANNEL_IN_MONO,
            AudioFormat.ENCODING_PCM_16BIT);
    audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, SAMPLE_RATE_HZ, AudioFormat.CHANNEL_IN_MONO,
            AudioFormat.ENCODING_PCM_16BIT, bufferSize);
}
 
Example 9
Source File: AudioRecorder.java    From euphony with Apache License 2.0 5 votes vote down vote up
/**
 * Constructor.
 * 
 * @param sampleRate
 *            The sample rate (e.g. 44100 Hz).
 */
public AudioRecorder(int sampleRate) {
	int bufferSize = AudioRecord.getMinBufferSize(sampleRate,
			AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT);
	
	audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC,
			sampleRate, AudioFormat.CHANNEL_CONFIGURATION_MONO,
			AudioFormat.ENCODING_PCM_16BIT, bufferSize);
	swtWindowing = false;
}
 
Example 10
Source File: MediaAudioEncoder.java    From UVCCameraZxing with Apache License 2.0 5 votes vote down vote up
@Override
 	public void run() {
 		try {
          final int buf_sz = AudioRecord.getMinBufferSize(
          	SAMPLE_RATE, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT) * 4;
          final AudioRecord audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC,
          	SAMPLE_RATE, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, buf_sz);
          try {
          	if (mIsCapturing) {
  				if (DEBUG) Log.v(TAG, "AudioThread:start audio recording");
               final byte[] buf = new byte[buf_sz];
               int readBytes;
               audioRecord.startRecording();
               try {
	    		while (mIsCapturing && !mRequestStop && !mIsEOS) {
	    			// read audio data from internal mic
	    			readBytes = audioRecord.read(buf, 0, buf_sz);
	    			if (readBytes > 0) {
	    			    // set audio data to encoder
	    				encode(buf, readBytes, getPTSUs());
	    				frameAvailableSoon();
	    			}
	    		}
   				frameAvailableSoon();
               } finally {
               	audioRecord.stop();
               }
          	}
          } finally {
          	audioRecord.release();
          }
 		} catch (final Exception e) {
 			Log.e(TAG, "AudioThread#run", e);
 		}
if (DEBUG) Log.v(TAG, "AudioThread:finished");
 	}
 
Example 11
Source File: RecordAudioTester.java    From PermissionAgent with Apache License 2.0 5 votes vote down vote up
private static AudioRecord findAudioRecord() {
    for (int rate : RATES) {
        for (short format : new short[] {AudioFormat.ENCODING_PCM_8BIT, AudioFormat.ENCODING_PCM_16BIT}) {
            for (short channel : new short[] {AudioFormat.CHANNEL_IN_MONO, AudioFormat.CHANNEL_IN_STEREO}) {
                int buffer = AudioRecord.getMinBufferSize(rate, channel, format);
                if (buffer != AudioRecord.ERROR_BAD_VALUE) {
                    AudioRecord recorder = new AudioRecord(MediaRecorder.AudioSource.MIC, rate, channel, format,
                        buffer);
                    if (recorder.getState() == AudioRecord.STATE_INITIALIZED) return recorder;
                }
            }
        }
    }
    return null;
}
 
Example 12
Source File: StreamPublisher.java    From AndroidInstantVideo with Apache License 2.0 5 votes vote down vote up
private StreamPublisherParam(int width, int height, int videoBitRate, int frameRate,
                            int iframeInterval, int samplingRate, int audioBitRate, int audioSource, int channelCfg) {
    this.width = width;
    this.height = height;
    this.videoBitRate = videoBitRate;
    this.frameRate = frameRate;
    this.iframeInterval = iframeInterval;
    this.samplingRate = samplingRate;
    this.audioBitRate = audioBitRate;
    this.audioBufferSize = AudioRecord.getMinBufferSize(samplingRate, channelCfg, AudioFormat.ENCODING_PCM_16BIT) * 2;
    this.audioSource = audioSource;
    this.channelCfg = channelCfg;
}
 
Example 13
Source File: AudioManagerAndroid.java    From 365browser with Apache License 2.0 5 votes vote down vote up
/**
* Returns the minimum frame size required for audio input.
*
* @param sampleRate sampling rate
* @param channels number of channels
*/
 @CalledByNative
 private static int getMinInputFrameSize(int sampleRate, int channels) {
     int channelConfig;
     if (channels == 1) {
         channelConfig = AudioFormat.CHANNEL_IN_MONO;
     } else if (channels == 2) {
         channelConfig = AudioFormat.CHANNEL_IN_STEREO;
     } else {
         return -1;
     }
     return AudioRecord.getMinBufferSize(
             sampleRate, channelConfig, AudioFormat.ENCODING_PCM_16BIT) / 2 / channels;
 }
 
Example 14
Source File: MyAudioRecord.java    From AndroidScreenShare with Apache License 2.0 4 votes vote down vote up
private void init(){
    int minBufferSize = AudioRecord.getMinBufferSize(mSampleRate, mChannelMode,
            mEncodeFormat);
    mAudioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC,
            mSampleRate, mChannelMode, mEncodeFormat, minBufferSize * 2);
}
 
Example 15
Source File: CheckPermission.java    From EasyPhotos with Apache License 2.0 4 votes vote down vote up
/**
 * 用于检测是否具有录音权限
 *
 * @return
 */
public static int getRecordState() {
    int minBuffer = AudioRecord.getMinBufferSize(44100, AudioFormat.CHANNEL_IN_MONO, AudioFormat
            .ENCODING_PCM_16BIT);
    AudioRecord audioRecord = new AudioRecord(MediaRecorder.AudioSource.DEFAULT, 44100, AudioFormat
            .CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, (minBuffer * 100));
    short[] point = new short[minBuffer];
    int readSize = 0;
    try {

        audioRecord.startRecording();//检测是否可以进入初始化状态
    } catch (Exception e) {
        if (audioRecord != null) {
            audioRecord.release();
            audioRecord = null;
        }
        return STATE_NO_PERMISSION;
    }
    if (audioRecord.getRecordingState() != AudioRecord.RECORDSTATE_RECORDING) {
        //6.0以下机型都会返回此状态,故使用时需要判断bulid版本
        //检测是否在录音中
        if (audioRecord != null) {
            audioRecord.stop();
            audioRecord.release();
            audioRecord = null;
            LogUtil.d("录音机被占用");
        }
        return STATE_RECORDING;
    } else {
        //检测是否可以获取录音结果

        readSize = audioRecord.read(point, 0, point.length);


        if (readSize <= 0) {
            if (audioRecord != null) {
                audioRecord.stop();
                audioRecord.release();
                audioRecord = null;

            }
            LogUtil.d("录音的结果为空");
            return STATE_NO_PERMISSION;

        } else {
            if (audioRecord != null) {
                audioRecord.stop();
                audioRecord.release();
                audioRecord = null;

            }

            return STATE_SUCCESS;
        }
    }
}
 
Example 16
Source File: AudioRecorder.java    From connectivity-samples with Apache License 2.0 4 votes vote down vote up
@Override
protected int getMinBufferSize(int sampleRate) {
  return AudioRecord.getMinBufferSize(
      sampleRate, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT);
}
 
Example 17
Source File: CheckPermission.java    From CameraView with Apache License 2.0 4 votes vote down vote up
/**
 * 用于检测是否具有录音权限
 *
 * @return
 */
public static int getRecordState() {
    int minBuffer = AudioRecord.getMinBufferSize(44100, AudioFormat.CHANNEL_IN_MONO, AudioFormat
            .ENCODING_PCM_16BIT);
    AudioRecord audioRecord = new AudioRecord(MediaRecorder.AudioSource.DEFAULT, 44100, AudioFormat
            .CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, (minBuffer * 100));
    short[] point = new short[minBuffer];
    int readSize = 0;
    try {

        audioRecord.startRecording();//检测是否可以进入初始化状态
    } catch (Exception e) {
        if (audioRecord != null) {
            audioRecord.release();
            audioRecord = null;
        }
        return STATE_NO_PERMISSION;
    }
    if (audioRecord.getRecordingState() != AudioRecord.RECORDSTATE_RECORDING) {
        //6.0以下机型都会返回此状态,故使用时需要判断bulid版本
        //检测是否在录音中
        if (audioRecord != null) {
            audioRecord.stop();
            audioRecord.release();
            audioRecord = null;
            Log.d("CheckAudioPermission", "录音机被占用");
        }
        return STATE_RECORDING;
    } else {
        //检测是否可以获取录音结果

        readSize = audioRecord.read(point, 0, point.length);


        if (readSize <= 0) {
            if (audioRecord != null) {
                audioRecord.stop();
                audioRecord.release();
                audioRecord = null;

            }
            Log.d("CheckAudioPermission", "录音的结果为空");
            return STATE_NO_PERMISSION;

        } else {
            if (audioRecord != null) {
                audioRecord.stop();
                audioRecord.release();
                audioRecord = null;

            }

            return STATE_SUCCESS;
        }
    }
}
 
Example 18
Source File: PermissionUtil.java    From AlbumCameraRecorder with MIT License 4 votes vote down vote up
/**
 * 用于检测是否具有录音权限
 *
 * @return 状态:是否具有
 */
public static int getRecordState() {
    int minBuffer = AudioRecord.getMinBufferSize(44100, AudioFormat.CHANNEL_IN_MONO, AudioFormat
            .ENCODING_PCM_16BIT);
    AudioRecord audioRecord = new AudioRecord(MediaRecorder.AudioSource.DEFAULT, 44100, AudioFormat
            .CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, (minBuffer * 100));
    short[] point = new short[minBuffer];
    int readSize;
    try {

        audioRecord.startRecording();//检测是否可以进入初始化状态
    } catch (Exception e) {
        if (audioRecord != null) {
            audioRecord.release();
            audioRecord = null;
        }
        return STATE_NO_PERMISSION;
    }
    if (audioRecord.getRecordingState() != AudioRecord.RECORDSTATE_RECORDING) {
        //6.0以下机型都会返回此状态,故使用时需要判断bulid版本
        //检测是否在录音中
        if (audioRecord != null) {
            audioRecord.stop();
            audioRecord.release();
            Log.d("CheckAudioPermission", "录音机被占用");
        }
        return STATE_RECORDING;
    } else {
        //检测是否可以获取录音结果

        readSize = audioRecord.read(point, 0, point.length);


        if (readSize <= 0) {
            if (audioRecord != null) {
                audioRecord.stop();
                audioRecord.release();

            }
            Log.d("CheckAudioPermission", "录音的结果为空");
            return STATE_NO_PERMISSION;

        } else {
            if (audioRecord != null) {
                audioRecord.stop();
                audioRecord.release();

            }

            return STATE_SUCCESS;
        }
    }
}
 
Example 19
Source File: Record.java    From SinVoiceDemo with Apache License 2.0 4 votes vote down vote up
public void start() {
    if (STATE_STOP == mState) {
        mState = STATE_START;

        switch (mChannel) {
        case CHANNEL_1:
            mChannelConfig = AudioFormat.CHANNEL_IN_MONO;
            break;
        case CHANNEL_2:
            mChannelConfig = AudioFormat.CHANNEL_IN_STEREO;
            break;
        }

        switch (mBits) {
        case BITS_8:
            mAudioEncoding = AudioFormat.ENCODING_PCM_8BIT;
            break;

        case BITS_16:
            mAudioEncoding = AudioFormat.ENCODING_PCM_16BIT;
            break;
        }

        int minBufferSize = AudioRecord.getMinBufferSize(mFrequence, mChannelConfig, mAudioEncoding);
        LogHelper.d(TAG, "minBufferSize:" + minBufferSize);

        AudioRecord record = new AudioRecord(MediaRecorder.AudioSource.MIC, mFrequence, mChannelConfig, mAudioEncoding, mBufferSize);
        record.startRecording();
        LogHelper.d(TAG, "record start");

        if (null != mCallback) {
            if (null != mListener) {
                mListener.onStartRecord();
            }

            while (STATE_START == mState) {
                BufferData data = mCallback.getRecordBuffer();
                if (null != data) {
                    if (null != data.byteData) {
                        int bufferReadResult = record.read(data.byteData, 0, mBufferSize);
                        data.setFilledSize(bufferReadResult);

                        mCallback.freeRecordBuffer(data);
                    } else {
                        // end of input
                        LogHelper.d(TAG, "get end input data, so stop");
                        break;
                    }
                } else {
                    LogHelper.d(TAG, "get null data");
                    break;
                }
            }

            if (null != mListener) {
                mListener.onStopRecord();
            }
        }

        record.stop();
        record.release();

        LogHelper.d(TAG, "record stop");
    }
}
 
Example 20
Source File: AudioCapture.java    From EvilsLive with MIT License 3 votes vote down vote up
public boolean startCapture(int audioSource, int sampleRateInHz, int channelConfig, int audioFormat) {

        if (mIsCaptureStarted) {
            Log.e(TAG, "hujd Capture already started !");
            return false;
        }

        mMinBufferSize = AudioRecord.getMinBufferSize(sampleRateInHz, channelConfig, audioFormat);

        if (mMinBufferSize == AudioRecord.ERROR_BAD_VALUE) {
            Log.e(TAG, "hujd Invalid parameter !");
            return false;
        }

        Log.e(TAG, "hujd getMinBufferSize = " + mMinBufferSize + " bytes !");

        mAudioRecord = new AudioRecord(audioSource, sampleRateInHz, channelConfig, audioFormat, mMinBufferSize);

        if (mAudioRecord.getState() == AudioRecord.STATE_UNINITIALIZED) {
            Log.e(TAG, "hujd AudioRecord initialize fail !");
            return false;
        }

        mAudioRecord.startRecording();


        mIsLoopExit = false;
        mCaptureThread = new Thread(new AudioCaptureRunnable());

        mCaptureThread.start();

        mIsCaptureStarted = true;

        Log.e(TAG, "hujd Start audio capture success !");
        return true;

    }