I'm trying to record and play audio using different devices with AudioRecord and AudioTrack and setting preferredDevice to set the devices to each.
audioRecord = AudioRecord(
MediaRecorder.AudioSource.VOICE_COMMUNICATION,
sampleRate,
AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_FLOAT,
frameSize * Float.SIZE_BYTES
)
audioRecord?.preferredDevice = mic
audioTrack = AudioTrack.Builder()
.setAudioAttributes(
AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_VOICE_COMMUNICATION)
.setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
.build()
)
.setAudioFormat(
AudioFormat.Builder()
.setEncoding(AudioFormat.ENCODING_PCM_FLOAT)
.setSampleRate(PLAYBACK_SAMPLE_RATE)
.setChannelMask(AudioFormat.CHANNEL_OUT_MONO)
.build()
)
.setBufferSizeInBytes(frameSize * Float.SIZE_BYTES * 2)
.build()
audioTrack?.preferredDevice = speaker
It works fine when both input and out are preferred to one device, but when selecting different devices, the mic(AudioRecord) is also using the speaker's preferred device. Even when I log the audioRecord?.routedDevice, it doesn't seem to change to the preferred device for AudioRecord but uses the same preferred AudioTrack.
Note: I'm trying to switch between a Wired headset, a Bluetooth device and the Android device's default audio hardware.
Any idea what could be the issue here? Or is it not possible to use two devices for input and output like in iOS?
You need to check if
setPreferredDevicereturns true.It returns false if the specified
AudioDeviceInfois non-null and does not correspond to a valid audio input/output device.I assumed
micandspeakeris not null because ifdeviceInfois null, default routing is restored.