Skip to content

Commit 71272f2

Browse files
VinayGuthalrlazo
authored andcommitted
fix emulator listening to itself (#6823)
1 parent dc118ad commit 71272f2

File tree

2 files changed

+31
-5
lines changed

2 files changed

+31
-5
lines changed

firebase-vertexai/src/main/kotlin/com/google/firebase/vertexai/type/AudioHelper.kt

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,21 @@ internal class AudioHelper {
6969
}
7070
}
7171

72+
fun stopRecording() {
73+
if (
74+
::audioRecord.isInitialized && audioRecord.recordingState == AudioRecord.RECORDSTATE_RECORDING
75+
) {
76+
audioRecord.stop()
77+
}
78+
}
79+
80+
fun start() {
81+
if (
82+
::audioRecord.isInitialized && audioRecord.recordingState != AudioRecord.RECORDSTATE_RECORDING
83+
) {
84+
audioRecord.startRecording()
85+
}
86+
}
7287
@RequiresPermission(Manifest.permission.RECORD_AUDIO)
7388
fun startRecording(): Flow<ByteArray> {
7489

@@ -110,10 +125,16 @@ internal class AudioHelper {
110125
return flow {
111126
val buffer = ByteArray(bufferSize)
112127
while (!stopRecording) {
113-
val bytesRead = audioRecord.read(buffer, 0, buffer.size)
114-
if (bytesRead > 0) {
115-
emit(buffer.copyOf(bytesRead))
128+
if (audioRecord.recordingState != AudioRecord.RECORDSTATE_RECORDING) {
129+
buffer.fill(0x00)
130+
continue
116131
}
132+
try {
133+
val bytesRead = audioRecord.read(buffer, 0, buffer.size)
134+
if (bytesRead > 0) {
135+
emit(buffer.copyOf(bytesRead))
136+
}
137+
} catch (_: Exception) {}
117138
}
118139
}
119140
}

firebase-vertexai/src/main/kotlin/com/google/firebase/vertexai/type/LiveSession.kt

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -183,8 +183,13 @@ internal constructor(
183183
private fun playServerResponseAudio() {
184184
CoroutineScope(backgroundDispatcher).launch {
185185
while (isRecording) {
186-
val x = playBackQueue.poll() ?: continue
187-
audioHelper?.playAudio(x)
186+
val data = playBackQueue.poll()
187+
if (data == null) {
188+
audioHelper?.start()
189+
continue
190+
}
191+
audioHelper?.stopRecording()
192+
audioHelper?.playAudio(data)
188193
}
189194
}
190195
}

0 commit comments

Comments
 (0)