知乎专栏 |
private AudioRecord getAudioRecord() { final int SAMPLE_RATE = 16000; final int WAVE_FRAM_SIZE = 20 * 2 * 16000 / 1000; //20ms audio for 16k/16bit/mono try { int bufferSize = AudioRecord.getMinBufferSize(16000, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT); // AudioRecord recorder = new AudioRecord(MediaRecorder.AudioSource.DEFAULT, 16000, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, bufferSize); AudioRecord recorder = new AudioRecord(MediaRecorder.AudioSource.DEFAULT, SAMPLE_RATE, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, WAVE_FRAM_SIZE * 4); if (recorder.getState() == AudioRecord.STATE_INITIALIZED) { return recorder; } } catch (Exception e) { Log.e(TAG, "Error in Audio Record"); } return null; }
当设备中有多个麦克风时,我们希望切换到另一个麦克风,可以采用此方法。
AudioRecord audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, 16000, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, 16000 * 4); AudioManager audioManager = (AudioManager) MainApplication.getContext().getSystemService(Context.AUDIO_SERVICE); AudioDeviceInfo[] audioDeviceInfos = new AudioDeviceInfo[]{}; audioDeviceInfos = audioManager.getDevices(AudioManager.GET_DEVICES_INPUTS); for (AudioDeviceInfo device : audioDeviceInfos) { if (device.getType() == AudioDeviceInfo.TYPE_USB_DEVICE && device.getProductName().equals("USB-Audio - USB PnP Sound Device")) { audioRecord.setPreferredDevice(device); Log.d(TAG, "Set microphone: " + device.getProductName()); } Log.d(TAG, device.getId() + " | " + device.getProductName() + " | " + device.getType()); } audioRecord.startRecording(); Log.d(TAG, "AudioRecord state: " + audioRecord.getState()); if (audioRecord.getState() != AudioRecord.STATE_INITIALIZED) { Log.e(TAG, "audio recorder not init"); } else { byte[] audioData = new byte[1024]; for (int i = 0; i < 100; i++) { int ret = audioRecord.read(audioData, 0, 1024); Log.d(TAG, String.valueOf(audioData)); } }