android.media.AudioRecord#STATE_INITIALIZED源码实例Demo

下面列出了android.media.AudioRecord#STATE_INITIALIZED 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

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;
    }
}
 
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;
}
 
源代码3 项目: bither-android   文件: UEntropyMic.java
@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."));
    }
}
 
源代码4 项目: permissions4m   文件: AudioRecordManager.java
/**
 * 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();
}
 
源代码5 项目: android-fskmodem   文件: MainActivity.java
@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();
}
 
源代码6 项目: Telegram   文件: AudioRecordJNI.java
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;
}
 
源代码7 项目: Jumble   文件: AudioInput.java
@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");
}
 
源代码8 项目: AndroidUSBCamera   文件: AACEncodeConsumer.java
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();
}
 
源代码9 项目: android-docs-samples   文件: VoiceRecorder.java
/**
 * 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;
}
 
源代码10 项目: guitar-tuner   文件: AudioProcessor.java
@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");
}
 
源代码11 项目: PermissionAgent   文件: RecordAudioTester.java
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;
}
 
源代码12 项目: media-for-mobile   文件: MicrophoneSource.java
@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();
}
 
源代码13 项目: EZFilter   文件: MediaAudioEncoder.java
/**
 * 查找可用的音频录制器
 *
 * @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;
}
 
源代码14 项目: Saiy-PS   文件: SaiyRecorder.java
/**
 * 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;
}
 
源代码15 项目: CameraV   文件: AACHelper.java
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;
}
 
源代码16 项目: Muzesto   文件: Timber5.java
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();
        }
    }
}
 
源代码17 项目: connectivity-samples   文件: AudioRecorder.java
/** 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();
}
 
源代码18 项目: android-fskmodem   文件: MainActivity.java
@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!");
	}
}
 
源代码19 项目: science-journal   文件: AudioSource.java
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();
          });
}
 
源代码20 项目: DeviceConnect-Android   文件: MicAACLATMEncoder.java
/**
 * 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();
}