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