优化代码
This commit is contained in:
parent
761e98f1b6
commit
201a60cf65
@ -268,13 +268,13 @@ class MainActivity : BaseViewModelActivity<ActivityMainBinding, MainViewModel>()
|
|||||||
Log.e("VoiceService", "Invalid min buffer size")
|
Log.e("VoiceService", "Invalid min buffer size")
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
val bufferSize = minBuf * 2
|
||||||
audioRecord = AudioRecord(
|
audioRecord = AudioRecord(
|
||||||
audioSource,
|
audioSource,
|
||||||
sampleRateInHz,
|
sampleRateInHz,
|
||||||
channelConfig,
|
channelConfig,
|
||||||
audioFormat,
|
audioFormat,
|
||||||
minBuf * 2
|
bufferSize
|
||||||
)
|
)
|
||||||
|
|
||||||
if (audioRecord?.state != AudioRecord.STATE_INITIALIZED) {
|
if (audioRecord?.state != AudioRecord.STATE_INITIALIZED) {
|
||||||
@ -304,39 +304,30 @@ class MainActivity : BaseViewModelActivity<ActivityMainBinding, MainViewModel>()
|
|||||||
|
|
||||||
|
|
||||||
//开始录音
|
//开始录音
|
||||||
fun startRecording() {
|
private fun startRecording() {
|
||||||
if (isRecording) return
|
if (isRecording) return
|
||||||
|
if (audioRecord == null && !initMicrophone()) return
|
||||||
|
|
||||||
if (audioRecord == null) {
|
try { audioRecord?.startRecording() } catch (e: IllegalStateException) { recreateAudioRecord(); return }
|
||||||
if (!initMicrophone()) {
|
|
||||||
Log.e("VoiceService", "startRecording: init failed")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
audioRecord?.startRecording()
|
|
||||||
} catch (e: IllegalStateException) {
|
|
||||||
Log.e("VoiceService", "startRecording failed, recreate", e)
|
|
||||||
recreateAudioRecord()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
isRecording = true
|
isRecording = true
|
||||||
|
|
||||||
lifecycleScope.launch(Dispatchers.IO) {
|
lifecycleScope.launch(Dispatchers.IO) {
|
||||||
val buf = ShortArray(512)
|
val buf = ShortArray(1024) // 32~64ms 够低延迟
|
||||||
|
val floatBuf = FloatArray(buf.size)
|
||||||
|
|
||||||
while (isRecording) {
|
while (isRecording) {
|
||||||
val n = audioRecord?.read(buf, 0, buf.size) ?: break
|
val read = audioRecord?.read(buf, 0, buf.size) ?: break
|
||||||
if (n > 0) {
|
if (read > 0) {
|
||||||
val raw = FloatArray(n) { buf[it] / 32768f }
|
// 避免每次都 new FloatArray,复用
|
||||||
voiceController?.acceptAudio(raw)
|
for (i in 0 until read) floatBuf[i] = buf[i] / 32768f
|
||||||
|
voiceController?.acceptAudio(floatBuf.copyOf(read))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
private fun recreateAudioRecord() {
|
private fun recreateAudioRecord() {
|
||||||
stopRecording()
|
stopRecording()
|
||||||
try {
|
try {
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user