Java Code Examples for android.media.AudioRecord#STATE_INITIALIZED

The following examples show how to use android.media.AudioRecord#STATE_INITIALIZED . 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: 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 2
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 3
Source File: AudioRecorder.java    From react-native-google-nearby-connection with MIT License 6 votes vote down vote up
public AudioRecord findAudioRecord() {
	for (int rate : AudioBuffer.POSSIBLE_SAMPLE_RATES) {
		for (short audioFormat : new short[] { AudioFormat.ENCODING_PCM_8BIT, AudioFormat.ENCODING_PCM_16BIT }) {
			for (short channelConfig : new short[] { AudioFormat.CHANNEL_IN_MONO, AudioFormat.CHANNEL_IN_STEREO }) {
				try {
					Log.d(TAG, "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(AudioSource.DEFAULT, rate, channelConfig, audioFormat, bufferSize);

						if (recorder.getState() == AudioRecord.STATE_INITIALIZED) {
							return recorder;
						}
					}
				} catch (Exception e) {
					Log.e(TAG, rate + "Exception, keep trying.",e);
				}
			}
		}
	}
	return null;
}
 
Example 4
Source File: UEntropyMic.java    From bither-android with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
    int minBufferSize = AudioRecord.getMinBufferSize(SamplePerSec, ChannelConfiguration,
            AudioEncoding);
    if (minBufferSize > MaxBufferSize) {
        bufferSizeBytes = minBufferSize;
    } else {
        bufferSizeBytes = (MaxBufferSize / minBufferSize) * minBufferSize;
    }
    audioRecord = new AudioRecord(android.media.MediaRecorder.AudioSource.MIC,
            SamplePerSec, ChannelConfiguration, AudioEncoding, bufferSizeBytes);
    if (audioRecord.getState() == AudioRecord.STATE_INITIALIZED) {
        audioRecord.startRecording();
        micHandler.post(readRunnable);
        visualizer.setVisibility(View.VISIBLE);
    } else {
        uncaughtException(Thread.currentThread(), new IllegalStateException
                ("startRecording() called on an " + "uninitialized AudioRecord."));
    }
}
 
Example 5
Source File: AudioRecordManager.java    From permissions4m with Apache License 2.0 6 votes vote down vote up
/**
 * stop record
 *
 * @throws IOException
 * @throws InterruptedException
 */
public void stopRecord() throws IOException, InterruptedException {
    // specially for OPPO、XIAOMI、MEIZU、HUAWEI and so on
    Thread.sleep(250);
    destroyThread();
    if (mRecorder != null) {
        if (mRecorder.getState() == AudioRecord.STATE_INITIALIZED) {
            mRecorder.stop();
        }
        if (mRecorder != null) {
            mRecorder.release();
        }
    }
    if (dos != null) {
        dos.flush();
        dos.close();
    }
    length = file.length();
    deleteFile();
}
 
Example 6
Source File: MainActivity.java    From android-fskmodem with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected void onDestroy() {
	
	mDecoder.stop();
	mEncoder.stop();
	
	if (mRecorder != null && mRecorder.getState() == AudioRecord.STATE_INITIALIZED)
	{
		mRecorder.stop();
		mRecorder.release();
	}
	
	if (mAudioTrack != null && mAudioTrack.getPlayState() == AudioTrack.STATE_INITIALIZED)
	{
		mAudioTrack.stop();
		mAudioTrack.release();
	}
	
	super.onDestroy();
}
 
Example 7
Source File: AudioRecordJNI.java    From Telegram with GNU General Public License v2.0 6 votes vote down vote up
public boolean start() {
	if(audioRecord==null || audioRecord.getState()!=AudioRecord.STATE_INITIALIZED)
		return false;
	try{
		if(thread==null){
				if(audioRecord==null)
					return false;
				audioRecord.startRecording();
			startThread();
		}else{
			audioRecord.startRecording();
		}
		return true;
	}catch(Exception x){
		VLog.e("Error initializing AudioRecord", x);
	}
	return false;
}
 
Example 8
Source File: AudioInput.java    From Jumble with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void run() {
    android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_URGENT_AUDIO);

    Log.i(Constants.TAG, "AudioInput: started");

    mAudioRecord.startRecording();

    if(mAudioRecord.getState() != AudioRecord.STATE_INITIALIZED)
        return;

    final short[] mAudioBuffer = new short[mFrameSize];
    // We loop when the 'recording' instance var is true instead of checking audio record state because we want to always cleanly shutdown.
    while(mRecording) {
        int shortsRead = mAudioRecord.read(mAudioBuffer, 0, mFrameSize);
        if(shortsRead > 0) {
            mListener.onAudioInputReceived(mAudioBuffer, mFrameSize);
        } else {
            Log.e(Constants.TAG, "Error fetching audio! AudioRecord error " + shortsRead);
        }
    }

    mAudioRecord.stop();

    Log.i(Constants.TAG, "AudioInput: stopped");
}
 
Example 9
Source File: AACEncodeConsumer.java    From AndroidUSBCamera with Apache License 2.0 6 votes vote down vote up
private void initAudioRecord(){
    if(DEBUG)
        Log.d(TAG,"AACEncodeConsumer-->开始采集音频");
    // 设置进程优先级
    Process.setThreadPriority(Process.THREAD_PRIORITY_AUDIO);
    int bufferSize = AudioRecord.getMinBufferSize(SAMPLE_RATE, AudioFormat.CHANNEL_IN_MONO,
            AudioFormat.ENCODING_PCM_16BIT);
    for (final int src: AUDIO_SOURCES) {
        try {
            mAudioRecord = new AudioRecord(src,
                    SAMPLE_RATE, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, bufferSize);
            if (mAudioRecord != null) {
                if (mAudioRecord.getState() != AudioRecord.STATE_INITIALIZED) {
                    mAudioRecord.release();
                    mAudioRecord = null;
                }
            }
        } catch (final Exception e) {
            mAudioRecord = null;
        }
        if (mAudioRecord != null) {
            break;
        }
    }
    mAudioRecord.startRecording();
}
 
Example 10
Source File: Timber5.java    From Muzesto with GNU General Public License v3.0 5 votes vote down vote up
private void checkPermissionsAndStart() {
    if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.RECORD_AUDIO},
                REQUEST_PERMISSION_RECORD_AUDIO);
    } else {
        initRecorder();
        if (audioRecord.getState() == AudioRecord.STATE_INITIALIZED) {
            startRecording();
        }
    }
}
 
Example 11
Source File: AACHelper.java    From CameraV with GNU General Public License v3.0 5 votes vote down vote up
private int initAudioRecord(int rate)
{
    try
    {
        Log.v("===========Attempting rate ", rate + "Hz, bits: " + audioFormat + ", channel: " + channelConfig);
        bufferSize = AudioRecord.getMinBufferSize(rate, channelConfig, audioFormat);

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

            if (recorder.getState() == AudioRecord.STATE_INITIALIZED)
            {
                Log.v("===========final rate ", rate + "Hz, bits: " + audioFormat + ", channel: " + channelConfig);

                return rate;
            }
        }
    }
    catch (Exception e)
    {
        Log.v("error", "" + rate);
    }

    return -1;
}
 
Example 12
Source File: SaiyRecorder.java    From Saiy-PS with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Initialise the Voice Recorder
 *
 * @return The audio record initialisation state.
 */
public int initialise() {

    int count = 0;

    while (count < 4) {
        count++;

        saiyAudio = new SaiyAudio(audioSource, sampleRateInHz, channelConfig, audioFormat,
                bufferSizeInBytes, enhance);

        if (saiyAudio.getState() == AudioRecord.STATE_INITIALIZED) {
            return AudioRecord.STATE_INITIALIZED;
        } else {
            if (DEBUG) {
                MyLog.w(CLS_NAME, "SaiyAudio reinitialisation attempt ~ " + count);
            }

            if (Looper.myLooper() != null && Looper.myLooper() != Looper.getMainLooper()) {

                // Give the audio object a small chance to sort itself out
                try {
                    Thread.sleep(250);
                } catch (InterruptedException e) {
                    if (DEBUG) {
                        MyLog.w(CLS_NAME, "SaiyAudio InterruptedException");
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    if (DEBUG) {
        MyLog.w(CLS_NAME, "SaiyAudio initialisation failed");
    }

    return AudioRecord.STATE_UNINITIALIZED;
}
 
Example 13
Source File: MediaAudioEncoder.java    From EZFilter with MIT License 5 votes vote down vote up
/**
 * 查找可用的音频录制器
 *
 * @return
 */
private AudioRecord findAudioRecord() {
    int[] samplingRates = new int[]{44100, 22050, 11025, 8000};
    int[] audioFormats = new int[]{
            AudioFormat.ENCODING_PCM_16BIT,
            AudioFormat.ENCODING_PCM_8BIT};
    int[] channelConfigs = new int[]{
            AudioFormat.CHANNEL_IN_STEREO,
            AudioFormat.CHANNEL_IN_MONO};

    for (int rate : samplingRates) {
        for (int format : audioFormats) {
            for (int config : channelConfigs) {
                try {
                    int bufferSize = AudioRecord.getMinBufferSize(rate, config, format);
                    if (bufferSize != AudioRecord.ERROR_BAD_VALUE) {
                        for (int source : AUDIO_SOURCES) {
                            AudioRecord recorder = new AudioRecord(source, rate, config, format, bufferSize * 4);
                            if (recorder.getState() == AudioRecord.STATE_INITIALIZED) {
                                mSamplingRate = rate;
                                return recorder;
                            }
                        }
                    }
                } catch (Exception e) {
                    Log.e(TAG, "Init AudioRecord Error." + Log.getStackTraceString(e));
                }
            }
        }
    }
    return null;
}
 
Example 14
Source File: MicrophoneSource.java    From media-for-mobile with Apache License 2.0 5 votes vote down vote up
@Override
public void start() {
    recorder = new AudioRecord(MediaRecorder.AudioSource.MIC, this.sampleRate, androidChannels, audioEncoding, minBufferSize * 4);

    int state = recorder.getState();

    if (state != AudioRecord.STATE_INITIALIZED) {
        throw new IllegalStateException("Failed to start AudioRecord! Used by another application?");
    }

    recorder.startRecording();

    super.start();
}
 
Example 15
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 16
Source File: AudioProcessor.java    From guitar-tuner with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {


    Log.d(TAG, "sampleRate="+mAudioRecord.getSampleRate());

    if(mAudioRecord.getState() != AudioRecord.STATE_INITIALIZED) {
        Log.e(TAG, "AudioRecord not initialized");
    }

    mAudioRecord.startRecording();
    int bufSize = 8192;
    final int sampleRate = mAudioRecord.getSampleRate();
    final short[] buffer = new short[bufSize];

    do {
        final int read = mAudioRecord.read(buffer, 0, bufSize);
        if (read > 0) {
            final double intensity = averageIntensity(buffer, read);

            int maxZeroCrossing = (int) (250 * (read / 8192) * (sampleRate / 44100.0));

            if (intensity >= 50 && zeroCrossingCount(buffer) <= maxZeroCrossing) {

                float freq = getPitch(buffer, read / 4, read, sampleRate, 50, 500);
                if (Math.abs(freq - mLastComputedFreq) <= 5f) {
                    mPitchDetectionListener.onPitchDetected(freq, intensity);
                }
                mLastComputedFreq = freq;


            }
        }
    } while (!mStop);

    Log.d(TAG, "Thread terminated");
}
 
Example 17
Source File: MainActivity.java    From android-fskmodem with GNU General Public License v3.0 4 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.activity_main);
	
	/// INIT FSK CONFIG
	
	try {
		mConfig = new FSKConfig(FSKConfig.SAMPLE_RATE_44100, FSKConfig.PCM_16BIT, FSKConfig.CHANNELS_MONO, FSKConfig.SOFT_MODEM_MODE_4, FSKConfig.THRESHOLD_20P);
	} catch (IOException e1) {
		e1.printStackTrace();
	}

	/// INIT FSK DECODER
	
	mDecoder = new FSKDecoder(mConfig, new FSKDecoderCallback() {
		
		@Override
		public void decoded(byte[] newData) {
			
			final String text = new String(newData);
			
			runOnUiThread(new Runnable() {
				public void run() {
					
					TextView view = ((TextView) findViewById(R.id.result));
					
					view.setText(view.getText()+text);
				}
			});
		}
	});
	
	///
	
	//make sure that the settings of the recorder match the settings of the decoder
	//most devices cant record anything but 44100 samples in 16bit PCM format...
	mBufferSize = AudioRecord.getMinBufferSize(FSKConfig.SAMPLE_RATE_44100, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT);
	
	//scale up the buffer... reading larger amounts of data
	//minimizes the chance of missing data because of thread priority
	mBufferSize *= 10;
	
	//again, make sure the recorder settings match the decoder settings
	mRecorder = new AudioRecord(AudioSource.MIC, FSKConfig.SAMPLE_RATE_44100, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, mBufferSize);

	if (mRecorder.getState() == AudioRecord.STATE_INITIALIZED) {
		mRecorder.startRecording();
		
		//start a thread to read the audio data
		Thread thread = new Thread(mRecordFeed);
		thread.setPriority(Thread.MAX_PRIORITY);
		thread.start();
	}
	else {
		Log.i("FSKDecoder", "Please check the recorder settings, something is wrong!");
	}
}
 
Example 18
Source File: AudioSource.java    From science-journal with Apache License 2.0 4 votes vote down vote up
private void start() {
  // FYI: the current thread holds lockAudioReceivers.
  // Use VOICE_COMMUNICATION to filter out audio coming from the speakers
  final AudioRecord audioRecord =
      new AudioRecord(
          MediaRecorder.AudioSource.VOICE_COMMUNICATION,
          SAMPLE_RATE_IN_HZ,
          CHANNEL_CONFIG,
          AUDIO_FORMAT,
          minBufferSizeInBytes);
  if (audioRecord.getState() != AudioRecord.STATE_INITIALIZED) {
    audioRecord.release();
    return;
  }

  audioRecord.startRecording();
  // AudioRecord.startRecording() logs an error but it has no return value and
  // doesn't throw an exception when someone else is using the mic.
  if (audioRecord.getRecordingState() != AudioRecord.RECORDSTATE_RECORDING) {
    audioRecord.release();
    return;
  }

  running.set(true);
  future =
      executorService.submit(
          () -> {
            short[] buffer = new short[minBufferSizeInBytes / 2];
            int offset = 0;
            boolean goodDataRead = false;

            while (running.get()) {
              int readShorts = audioRecord.read(buffer, offset, buffer.length - offset);
              // On some devices (Moto E, for example) we get a bunch of zeros when we first
              // start reading. Ignore those zeros.
              if (!goodDataRead) {
                int countLeadingZeros = 0;
                while (countLeadingZeros < readShorts && buffer[countLeadingZeros] == 0) {
                  countLeadingZeros++;
                }
                if (countLeadingZeros > 0) {
                  if (readShorts > countLeadingZeros) {
                    System.arraycopy(
                        buffer, countLeadingZeros, buffer, 0, readShorts - countLeadingZeros);
                  }
                  readShorts -= countLeadingZeros;
                }
                goodDataRead = (readShorts > 0);
              }
              offset += readShorts;
              // If the buffer is full, call the Receivers.
              if (offset == buffer.length) {
                synchronized (lockAudioReceivers) {
                  for (AudioReceiver audioReceiver : audioReceivers) {
                    audioReceiver.onReceiveAudio(buffer);
                  }
                }
                offset = 0;
              }
            }

            audioRecord.stop();
            audioRecord.release();
          });
}
 
Example 19
Source File: MicAACLATMEncoder.java    From DeviceConnect-Android with MIT License 4 votes vote down vote up
/**
 * AudioRecord を開始します.
 */
private void startAudioRecord() {
    AudioQuality audioQuality = getAudioQuality();

    mBufferSize = AudioRecord.getMinBufferSize(audioQuality.getSamplingRate(),
            audioQuality.getChannel(), audioQuality.getFormat()) * 2;

    if (DEBUG) {
        Log.d(TAG, "AudioQuality: " + audioQuality);
    }

    mMuteBuffer = new byte[mBufferSize];

    mAudioRecord = new AudioRecord(MediaRecorder.AudioSource.DEFAULT,
            audioQuality.getSamplingRate(),
            audioQuality.getChannel(),
            audioQuality.getFormat(),
            mBufferSize);

    if (mAudioRecord.getState() != AudioRecord.STATE_INITIALIZED) {
        postOnError(new MediaEncoderException("AudioRecord is already initialized."));
        return;
    }

    if (mAudioQuality.isUseAEC() && AcousticEchoCanceler.isAvailable()) {
        // ノイズキャンセラー
        mEchoCanceler = AcousticEchoCanceler.create(mAudioRecord.getAudioSessionId());
        if (mEchoCanceler != null) {
            int ret = mEchoCanceler.setEnabled(true);
            if (ret != AudioEffect.SUCCESS) {
                if (DEBUG) {
                    Log.w(TAG, "AcousticEchoCanceler is not supported.");
                }
            }
        }
    }

    mAudioRecord.startRecording();

    mAudioThread = new AudioRecordThread();
    mAudioThread.setName("MicAACLATMEncoder");
    mAudioThread.start();
}
 
Example 20
Source File: AudioRecorder.java    From connectivity-samples with Apache License 2.0 4 votes vote down vote up
/** Starts recording audio. */
public void start() {
  if (isRecording()) {
    Log.w(TAG, "Already running");
    return;
  }

  mAlive = true;
  mThread =
      new Thread() {
        @Override
        public void run() {
          setThreadPriority(THREAD_PRIORITY_AUDIO);

          Buffer buffer = new Buffer();
          AudioRecord record =
              new AudioRecord(
                  MediaRecorder.AudioSource.DEFAULT,
                  buffer.sampleRate,
                  AudioFormat.CHANNEL_IN_MONO,
                  AudioFormat.ENCODING_PCM_16BIT,
                  buffer.size);

          if (record.getState() != AudioRecord.STATE_INITIALIZED) {
            Log.w(TAG, "Failed to start recording");
            mAlive = false;
            return;
          }

          record.startRecording();

          // While we're running, we'll read the bytes from the AudioRecord and write them
          // to our output stream.
          try {
            while (isRecording()) {
              int len = record.read(buffer.data, 0, buffer.size);
              if (len >= 0 && len <= buffer.size) {
                mOutputStream.write(buffer.data, 0, len);
                mOutputStream.flush();
              } else {
                Log.w(TAG, "Unexpected length returned: " + len);
              }
            }
          } catch (IOException e) {
            Log.e(TAG, "Exception with recording stream", e);
          } finally {
            stopInternal();
            try {
              record.stop();
            } catch (IllegalStateException e) {
              Log.e(TAG, "Failed to stop AudioRecord", e);
            }
            record.release();
          }
        }
      };
  mThread.start();
}