I'm using AudioTrack to play a series of audio data with 2s delay, but has no effect, the audio still play immediately, HERE IS MY CODE:
private fun delayOutput() {
CoroutineScope(Dispatchers.Default).launch {
withContext(Dispatchers.IO) {
delay(2000)
while (isRecording) {
val item = if (cachedBuffers.isNotEmpty()) {
cachedBuffers.first()
} else {
null
}
if (item != null) {
var writeRes: Int? = 0
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (item is ShortArray) {
writeRes = audioTrack?.write(item, 0, item.size, WRITE_NON_BLOCKING)
}
}
cachedBuffers.removeAt(0)
}
delay(100)
}
}
}
}
I print buffer's read time, it really is about 2s delay when write to audioTrack, i have no idea what's the matter.
I find the reason, because audiotrack is not init correct, correct code beside:
audioTrack = AudioTrack(AudioManager.STREAM_SYSTEM, sampleRateInHz, AudioFormat.CHANNEL_OUT_MONO, audioFormat, bufferSize * 4, AudioTrack.MODE_STREAM)