react-native-voice-bot-sdk 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +57 -0
- package/LICENSE +21 -0
- package/README.md +438 -2
- package/android/build.gradle +15 -0
- package/android/src/main/AndroidManifest.xml +16 -0
- package/android/src/main/java/expo/modules/voicebot/VoiceBotAudioModule.kt +416 -0
- package/android/src/main/java/expo/modules/voicebot/VoiceBotMicService.kt +107 -0
- package/app.plugin.js +1 -0
- package/build/NativeAudio.d.ts +24 -0
- package/build/NativeAudio.js +1 -0
- package/build/VoiceBotClient.d.ts +231 -0
- package/build/VoiceBotClient.js +1 -0
- package/build/audio/noiseGate.d.ts +83 -0
- package/build/audio/noiseGate.js +1 -0
- package/build/base64.d.ts +6 -0
- package/build/base64.js +1 -0
- package/build/expo-router.d.ts +16 -0
- package/build/expo-router.js +1 -0
- package/build/index.d.ts +20 -0
- package/build/index.js +1 -0
- package/build/logger.d.ts +35 -0
- package/build/logger.js +1 -0
- package/build/navigation/callbackNavigation.d.ts +28 -0
- package/build/navigation/callbackNavigation.js +1 -0
- package/build/navigation/reactNavigation.d.ts +33 -0
- package/build/navigation/reactNavigation.js +1 -0
- package/build/navigation/state.d.ts +20 -0
- package/build/navigation/state.js +1 -0
- package/build/navigation/types.d.ts +27 -0
- package/build/navigation/types.js +1 -0
- package/build/protocol.d.ts +108 -0
- package/build/protocol.js +1 -0
- package/build/react/VoiceBotProvider.d.ts +52 -0
- package/build/react/VoiceBotProvider.js +1 -0
- package/build/react/VoiceBotWidget.d.ts +29 -0
- package/build/react/VoiceBotWidget.js +1 -0
- package/build/react/useVoiceBot.d.ts +17 -0
- package/build/react/useVoiceBot.js +1 -0
- package/docs/INTEGRATION.md +189 -0
- package/docs/PROTOCOL.md +271 -0
- package/expo-module.config.json +9 -0
- package/ios/VoiceBotAudio.podspec +25 -0
- package/ios/VoiceBotAudioModule.swift +219 -0
- package/package.json +76 -4
- package/plugin/withVoiceBot.js +137 -0
|
@@ -0,0 +1,416 @@
|
|
|
1
|
+
package expo.modules.voicebot
|
|
2
|
+
|
|
3
|
+
import android.Manifest
|
|
4
|
+
import android.annotation.SuppressLint
|
|
5
|
+
import android.content.pm.PackageManager
|
|
6
|
+
import android.content.Context
|
|
7
|
+
import android.media.AudioAttributes
|
|
8
|
+
import android.media.AudioFocusRequest
|
|
9
|
+
import android.media.AudioManager
|
|
10
|
+
import android.os.Build
|
|
11
|
+
import android.os.Handler
|
|
12
|
+
import android.os.Looper
|
|
13
|
+
import android.media.AudioFormat
|
|
14
|
+
import android.media.AudioRecord
|
|
15
|
+
import android.media.AudioTrack
|
|
16
|
+
import android.media.MediaRecorder
|
|
17
|
+
import android.media.audiofx.AcousticEchoCanceler
|
|
18
|
+
import android.media.audiofx.AutomaticGainControl
|
|
19
|
+
import android.media.audiofx.NoiseSuppressor
|
|
20
|
+
import android.util.Base64
|
|
21
|
+
import android.util.Log
|
|
22
|
+
import androidx.core.content.ContextCompat
|
|
23
|
+
import expo.modules.kotlin.exception.CodedException
|
|
24
|
+
import expo.modules.kotlin.modules.Module
|
|
25
|
+
import expo.modules.kotlin.modules.ModuleDefinition
|
|
26
|
+
import java.util.concurrent.ExecutorService
|
|
27
|
+
import java.util.concurrent.Executors
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Raw PCM mic capture and playback for the voice bot SDK.
|
|
31
|
+
*
|
|
32
|
+
* Capture: PCM s16le, 16 kHz, mono, from the best voice source (VOICE_COMMUNICATION first)
|
|
33
|
+
* with echo cancellation, gain control and noise suppression. Exactly one 640-byte (20 ms)
|
|
34
|
+
* frame per `onAudioFrame` event, read and emitted from one thread, so frames are in order
|
|
35
|
+
* with no gaps.
|
|
36
|
+
*
|
|
37
|
+
* Playback: base64 PCM s16le 16 kHz mono chunks are queued and written in order to a
|
|
38
|
+
* streaming AudioTrack.
|
|
39
|
+
*/
|
|
40
|
+
class VoiceBotAudioModule : Module() {
|
|
41
|
+
companion object {
|
|
42
|
+
private const val TAG = "VoiceBotAudio"
|
|
43
|
+
const val SAMPLE_RATE = 16000
|
|
44
|
+
const val FRAME_BYTES = SAMPLE_RATE / 50 * 2 // 640 bytes = 20 ms
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
private val lock = Any()
|
|
48
|
+
@Volatile private var recording = false
|
|
49
|
+
private var audioRecord: AudioRecord? = null
|
|
50
|
+
private var recordThread: Thread? = null
|
|
51
|
+
private val effects = mutableListOf<android.media.audiofx.AudioEffect>()
|
|
52
|
+
|
|
53
|
+
private var audioTrack: AudioTrack? = null
|
|
54
|
+
private var playbackExecutor: ExecutorService? = null
|
|
55
|
+
/** Bumped by stopPlayback(); queued or running writes from before a stop are dropped. */
|
|
56
|
+
@Volatile private var playbackGeneration = 0
|
|
57
|
+
|
|
58
|
+
override fun definition() = ModuleDefinition {
|
|
59
|
+
Name("VoiceBotAudio")
|
|
60
|
+
|
|
61
|
+
Events("onAudioFrame", "onAudioError", "onAudioInterruption")
|
|
62
|
+
|
|
63
|
+
Constants(
|
|
64
|
+
"sampleRate" to SAMPLE_RATE,
|
|
65
|
+
"frameBytes" to FRAME_BYTES
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
Function("getAppInfo") {
|
|
69
|
+
val ctx = appContext.reactContext
|
|
70
|
+
mapOf("packageName" to (ctx?.packageName ?: ""))
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
Function("hasPermission") { hasMicPermission() }
|
|
74
|
+
|
|
75
|
+
AsyncFunction("startRecording") { startRecording() }
|
|
76
|
+
|
|
77
|
+
Function("stopRecording") { stopRecording() }
|
|
78
|
+
|
|
79
|
+
Function("isRecording") { recording }
|
|
80
|
+
|
|
81
|
+
/** Queues base64 PCM s16le mono. `rate` = its sample rate (8000-48000), default 16000. */
|
|
82
|
+
Function("enqueuePlayback") { base64: String, rate: Int? -> enqueuePlayback(base64, rate ?: SAMPLE_RATE) }
|
|
83
|
+
|
|
84
|
+
Function("stopPlayback") { stopPlayback() }
|
|
85
|
+
|
|
86
|
+
/** A random id saved on the device (SharedPreferences), the same across app launches. */
|
|
87
|
+
Function("getPersistentId") { key: String -> persistentId(key) }
|
|
88
|
+
|
|
89
|
+
/** Foreground service that keeps the mic working while the app is in the background. */
|
|
90
|
+
Function("startBackgroundService") { title: String, text: String ->
|
|
91
|
+
val ctx = appContext.reactContext ?: return@Function false
|
|
92
|
+
VoiceBotMicService.start(ctx, title, text)
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
Function("stopBackgroundService") {
|
|
96
|
+
appContext.reactContext?.let { VoiceBotMicService.stop(it) }
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Gives audio focus back once the bot has finished speaking. */
|
|
100
|
+
Function("releaseAudioFocus") { abandonFocus() }
|
|
101
|
+
|
|
102
|
+
OnDestroy {
|
|
103
|
+
stopCallWatch()
|
|
104
|
+
abandonFocus()
|
|
105
|
+
appContext.reactContext?.let { VoiceBotMicService.stop(it) }
|
|
106
|
+
stopRecording()
|
|
107
|
+
stopPlayback()
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
private fun persistentId(key: String): String {
|
|
112
|
+
val ctx = appContext.reactContext ?: return java.util.UUID.randomUUID().toString()
|
|
113
|
+
val prefs = ctx.getSharedPreferences("expo.modules.voicebot", android.content.Context.MODE_PRIVATE)
|
|
114
|
+
prefs.getString(key, null)?.let { return it }
|
|
115
|
+
val id = java.util.UUID.randomUUID().toString()
|
|
116
|
+
prefs.edit().putString(key, id).apply()
|
|
117
|
+
Log.i(TAG, "Created persistent id '$key'")
|
|
118
|
+
return id
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
private fun hasMicPermission(): Boolean {
|
|
122
|
+
val ctx = appContext.reactContext ?: return false
|
|
123
|
+
return ContextCompat.checkSelfPermission(ctx, Manifest.permission.RECORD_AUDIO) ==
|
|
124
|
+
PackageManager.PERMISSION_GRANTED
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
@SuppressLint("MissingPermission")
|
|
128
|
+
private fun startRecording() {
|
|
129
|
+
synchronized(lock) {
|
|
130
|
+
if (recording) return
|
|
131
|
+
if (!hasMicPermission()) {
|
|
132
|
+
throw CodedException("ERR_MIC_PERMISSION", "RECORD_AUDIO permission not granted", null)
|
|
133
|
+
}
|
|
134
|
+
val minBuf = AudioRecord.getMinBufferSize(
|
|
135
|
+
SAMPLE_RATE, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT
|
|
136
|
+
)
|
|
137
|
+
val bufferSize = minBuf.coerceAtLeast(4096) * 2
|
|
138
|
+
val record = createRecorder(bufferSize)
|
|
139
|
+
?: throw CodedException("ERR_MIC_INIT", "AudioRecord failed to initialize", null)
|
|
140
|
+
enableEnhancements(record.audioSessionId)
|
|
141
|
+
record.startRecording()
|
|
142
|
+
audioRecord = record
|
|
143
|
+
recording = true
|
|
144
|
+
|
|
145
|
+
recordThread = Thread({ readLoop(record) }, "VoiceBotMic").apply {
|
|
146
|
+
priority = Thread.MAX_PRIORITY
|
|
147
|
+
start()
|
|
148
|
+
}
|
|
149
|
+
Log.i(TAG, "Recording started (16 kHz mono, $FRAME_BYTES-byte frames)")
|
|
150
|
+
startCallWatch()
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** Reads exactly one 640-byte frame at a time (handling partial reads) and emits it. */
|
|
155
|
+
private fun readLoop(record: AudioRecord) {
|
|
156
|
+
val frame = ByteArray(FRAME_BYTES)
|
|
157
|
+
var filled = 0
|
|
158
|
+
while (recording) {
|
|
159
|
+
val n = record.read(frame, filled, FRAME_BYTES - filled)
|
|
160
|
+
if (n > 0) {
|
|
161
|
+
filled += n
|
|
162
|
+
if (filled == FRAME_BYTES) {
|
|
163
|
+
sendEvent("onAudioFrame", mapOf("data" to Base64.encodeToString(frame, Base64.NO_WRAP)))
|
|
164
|
+
filled = 0
|
|
165
|
+
}
|
|
166
|
+
} else if (n < 0) {
|
|
167
|
+
Log.e(TAG, "AudioRecord.read failed: $n")
|
|
168
|
+
sendEvent("onAudioError", mapOf("message" to "AudioRecord.read failed: $n"))
|
|
169
|
+
break
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
@SuppressLint("MissingPermission")
|
|
175
|
+
private fun createRecorder(bufferSize: Int): AudioRecord? {
|
|
176
|
+
val sources = listOf(
|
|
177
|
+
MediaRecorder.AudioSource.VOICE_COMMUNICATION,
|
|
178
|
+
MediaRecorder.AudioSource.VOICE_RECOGNITION,
|
|
179
|
+
MediaRecorder.AudioSource.MIC,
|
|
180
|
+
MediaRecorder.AudioSource.DEFAULT
|
|
181
|
+
)
|
|
182
|
+
for (source in sources) {
|
|
183
|
+
try {
|
|
184
|
+
val r = AudioRecord(
|
|
185
|
+
source, SAMPLE_RATE, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, bufferSize
|
|
186
|
+
)
|
|
187
|
+
if (r.state == AudioRecord.STATE_INITIALIZED) {
|
|
188
|
+
Log.i(TAG, "Audio source: ${sourceName(source)}")
|
|
189
|
+
return r
|
|
190
|
+
}
|
|
191
|
+
r.release()
|
|
192
|
+
} catch (e: Exception) {
|
|
193
|
+
Log.w(TAG, "Audio source ${sourceName(source)} unavailable: ${e.message}")
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
return null
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
private fun sourceName(source: Int): String = when (source) {
|
|
200
|
+
MediaRecorder.AudioSource.VOICE_COMMUNICATION -> "VOICE_COMMUNICATION"
|
|
201
|
+
MediaRecorder.AudioSource.VOICE_RECOGNITION -> "VOICE_RECOGNITION"
|
|
202
|
+
MediaRecorder.AudioSource.MIC -> "MIC"
|
|
203
|
+
MediaRecorder.AudioSource.DEFAULT -> "DEFAULT"
|
|
204
|
+
else -> source.toString()
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
private fun enableEnhancements(sessionId: Int) {
|
|
208
|
+
val on = mutableListOf<String>()
|
|
209
|
+
try {
|
|
210
|
+
if (AcousticEchoCanceler.isAvailable()) AcousticEchoCanceler.create(sessionId)?.let { it.enabled = true; effects.add(it); on.add("echo cancel") }
|
|
211
|
+
if (AutomaticGainControl.isAvailable()) AutomaticGainControl.create(sessionId)?.let { it.enabled = true; effects.add(it); on.add("gain control") }
|
|
212
|
+
if (NoiseSuppressor.isAvailable()) NoiseSuppressor.create(sessionId)?.let { it.enabled = true; effects.add(it); on.add("noise suppression") }
|
|
213
|
+
} catch (e: Exception) {
|
|
214
|
+
Log.w(TAG, "Audio effects unavailable: ${e.message}")
|
|
215
|
+
}
|
|
216
|
+
Log.i(TAG, "Audio effects: ${if (on.isEmpty()) "none available" else on.joinToString(", ")}")
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
private fun stopRecording() {
|
|
220
|
+
val thread: Thread?
|
|
221
|
+
val record: AudioRecord?
|
|
222
|
+
synchronized(lock) {
|
|
223
|
+
if (!recording && audioRecord == null) return
|
|
224
|
+
recording = false
|
|
225
|
+
thread = recordThread
|
|
226
|
+
record = audioRecord
|
|
227
|
+
recordThread = null
|
|
228
|
+
audioRecord = null
|
|
229
|
+
}
|
|
230
|
+
try { record?.stop() } catch (e: IllegalStateException) { Log.w(TAG, "stop: ${e.message}") }
|
|
231
|
+
try { thread?.join(500) } catch (_: InterruptedException) {}
|
|
232
|
+
record?.release()
|
|
233
|
+
effects.forEach { try { it.release() } catch (_: Exception) {} }
|
|
234
|
+
effects.clear()
|
|
235
|
+
stopCallWatch()
|
|
236
|
+
Log.i(TAG, "Recording stopped")
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/** Returns a playing AudioTrack for `rate`; a track at another rate is replaced. */
|
|
240
|
+
private fun ensureTrack(rate: Int): AudioTrack {
|
|
241
|
+
audioTrack?.let {
|
|
242
|
+
if (it.state == AudioTrack.STATE_INITIALIZED && it.sampleRate == rate) return it
|
|
243
|
+
Log.i(TAG, "Playback sample rate ${it.sampleRate} -> $rate Hz")
|
|
244
|
+
try { it.stop() } catch (_: Exception) {}
|
|
245
|
+
it.release()
|
|
246
|
+
audioTrack = null
|
|
247
|
+
}
|
|
248
|
+
val minBuf = AudioTrack.getMinBufferSize(
|
|
249
|
+
rate, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT
|
|
250
|
+
)
|
|
251
|
+
val track = AudioTrack.Builder()
|
|
252
|
+
.setAudioAttributes(
|
|
253
|
+
AudioAttributes.Builder()
|
|
254
|
+
.setUsage(AudioAttributes.USAGE_MEDIA)
|
|
255
|
+
.setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
|
|
256
|
+
.build()
|
|
257
|
+
)
|
|
258
|
+
.setAudioFormat(
|
|
259
|
+
AudioFormat.Builder()
|
|
260
|
+
.setSampleRate(rate)
|
|
261
|
+
.setChannelMask(AudioFormat.CHANNEL_OUT_MONO)
|
|
262
|
+
.setEncoding(AudioFormat.ENCODING_PCM_16BIT)
|
|
263
|
+
.build()
|
|
264
|
+
)
|
|
265
|
+
.setBufferSizeInBytes(minBuf.coerceAtLeast(4096) * 2)
|
|
266
|
+
.setTransferMode(AudioTrack.MODE_STREAM)
|
|
267
|
+
.build()
|
|
268
|
+
track.play()
|
|
269
|
+
audioTrack = track
|
|
270
|
+
requestFocus()
|
|
271
|
+
return track
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
private fun enqueuePlayback(base64: String, requestedRate: Int) {
|
|
275
|
+
if (base64.isEmpty()) return
|
|
276
|
+
val rate = if (requestedRate in 8000..48000) requestedRate else SAMPLE_RATE
|
|
277
|
+
val pcm = try { Base64.decode(base64, Base64.DEFAULT) } catch (e: IllegalArgumentException) {
|
|
278
|
+
sendEvent("onAudioError", mapOf("message" to "Bad base64 in reply buffer"))
|
|
279
|
+
return
|
|
280
|
+
}
|
|
281
|
+
val (executor, gen) = synchronized(lock) {
|
|
282
|
+
(playbackExecutor ?: Executors.newSingleThreadExecutor().also { playbackExecutor = it }) to playbackGeneration
|
|
283
|
+
}
|
|
284
|
+
executor.execute {
|
|
285
|
+
if (gen != playbackGeneration) return@execute
|
|
286
|
+
try {
|
|
287
|
+
val track = synchronized(lock) { if (gen == playbackGeneration) ensureTrack(rate) else null } ?: return@execute
|
|
288
|
+
// Odd byte counts would shift every following sample; drop a trailing odd byte.
|
|
289
|
+
val len = pcm.size - (pcm.size % 2)
|
|
290
|
+
var off = 0
|
|
291
|
+
while (off < len && gen == playbackGeneration) {
|
|
292
|
+
// Write in ~100 ms pieces so a stop takes effect quickly.
|
|
293
|
+
val w = track.write(pcm, off, minOf(len - off, rate / 5))
|
|
294
|
+
if (w <= 0) break
|
|
295
|
+
off += w
|
|
296
|
+
}
|
|
297
|
+
} catch (e: Exception) {
|
|
298
|
+
if (gen != playbackGeneration) return@execute // stopped while writing
|
|
299
|
+
Log.e(TAG, "Playback failed: ${e.message}")
|
|
300
|
+
sendEvent("onAudioError", mapOf("message" to "Playback failed: ${e.message}"))
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
private fun stopPlayback() {
|
|
306
|
+
val (executor, track) = synchronized(lock) {
|
|
307
|
+
playbackGeneration++
|
|
308
|
+
val e = playbackExecutor
|
|
309
|
+
val t = audioTrack
|
|
310
|
+
playbackExecutor = null
|
|
311
|
+
audioTrack = null
|
|
312
|
+
e to t
|
|
313
|
+
}
|
|
314
|
+
executor?.shutdownNow()
|
|
315
|
+
track?.let {
|
|
316
|
+
try { it.pause(); it.flush(); it.stop() } catch (_: Exception) {}
|
|
317
|
+
it.release()
|
|
318
|
+
Log.i(TAG, "Playback stopped")
|
|
319
|
+
}
|
|
320
|
+
abandonFocus()
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
// ---------- audio focus (other apps' audio) and phone calls ----------
|
|
324
|
+
|
|
325
|
+
private val mainHandler = Handler(Looper.getMainLooper())
|
|
326
|
+
private var focusRequest: AudioFocusRequest? = null
|
|
327
|
+
private var hasFocus = false
|
|
328
|
+
|
|
329
|
+
private fun audioManager(): AudioManager? =
|
|
330
|
+
appContext.reactContext?.getSystemService(Context.AUDIO_SERVICE) as? AudioManager
|
|
331
|
+
|
|
332
|
+
private val focusListener = AudioManager.OnAudioFocusChangeListener { change ->
|
|
333
|
+
when (change) {
|
|
334
|
+
AudioManager.AUDIOFOCUS_LOSS, AudioManager.AUDIOFOCUS_LOSS_TRANSIENT -> {
|
|
335
|
+
// Another app (music, video, a call) took the audio: stop the bot's voice.
|
|
336
|
+
Log.i(TAG, "Audio focus lost ($change): stopping reply audio")
|
|
337
|
+
hasFocus = false
|
|
338
|
+
stopPlayback()
|
|
339
|
+
sendEvent("onAudioInterruption", mapOf("reason" to "focus_lost"))
|
|
340
|
+
}
|
|
341
|
+
AudioManager.AUDIOFOCUS_GAIN -> Log.i(TAG, "Audio focus gained")
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
/** Asks other apps to lower their audio (duck) while the bot speaks. */
|
|
346
|
+
private fun requestFocus() {
|
|
347
|
+
if (hasFocus) return
|
|
348
|
+
val am = audioManager() ?: return
|
|
349
|
+
val attrs = AudioAttributes.Builder()
|
|
350
|
+
.setUsage(AudioAttributes.USAGE_MEDIA)
|
|
351
|
+
.setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
|
|
352
|
+
.build()
|
|
353
|
+
val result = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
|
354
|
+
val req = AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK)
|
|
355
|
+
.setAudioAttributes(attrs)
|
|
356
|
+
.setOnAudioFocusChangeListener(focusListener, mainHandler)
|
|
357
|
+
.build()
|
|
358
|
+
focusRequest = req
|
|
359
|
+
am.requestAudioFocus(req)
|
|
360
|
+
} else {
|
|
361
|
+
@Suppress("DEPRECATION")
|
|
362
|
+
am.requestAudioFocus(focusListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK)
|
|
363
|
+
}
|
|
364
|
+
hasFocus = result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED
|
|
365
|
+
Log.i(TAG, if (hasFocus) "Audio focus granted (other apps duck)" else "Audio focus refused ($result)")
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
private fun abandonFocus() {
|
|
369
|
+
if (!hasFocus) return
|
|
370
|
+
val am = audioManager() ?: return
|
|
371
|
+
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
|
372
|
+
focusRequest?.let { am.abandonAudioFocusRequest(it) }
|
|
373
|
+
} else {
|
|
374
|
+
@Suppress("DEPRECATION") am.abandonAudioFocus(focusListener)
|
|
375
|
+
}
|
|
376
|
+
hasFocus = false
|
|
377
|
+
Log.i(TAG, "Audio focus released")
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
// Phone calls: the audio mode changes to RINGTONE / IN_CALL / IN_COMMUNICATION. Checked every
|
|
381
|
+
// 500 ms while the mic is on (no phone-state permission needed).
|
|
382
|
+
private var lastMode = AudioManager.MODE_NORMAL
|
|
383
|
+
private var inCall = false
|
|
384
|
+
private val callWatch = object : Runnable {
|
|
385
|
+
override fun run() {
|
|
386
|
+
val mode = audioManager()?.mode ?: AudioManager.MODE_NORMAL
|
|
387
|
+
if (mode != lastMode) {
|
|
388
|
+
lastMode = mode
|
|
389
|
+
val call = mode == AudioManager.MODE_RINGTONE || mode == AudioManager.MODE_IN_CALL ||
|
|
390
|
+
mode == AudioManager.MODE_IN_COMMUNICATION || mode == AudioManager.MODE_CALL_SCREENING
|
|
391
|
+
if (call != inCall) {
|
|
392
|
+
inCall = call
|
|
393
|
+
Log.i(TAG, if (call) "Phone call started (audio mode $mode)" else "Phone call ended")
|
|
394
|
+
if (call) stopPlayback()
|
|
395
|
+
sendEvent("onAudioInterruption", mapOf("reason" to if (call) "call_started" else "call_ended"))
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
mainHandler.postDelayed(this, 500)
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
private fun startCallWatch() {
|
|
403
|
+
lastMode = audioManager()?.mode ?: AudioManager.MODE_NORMAL
|
|
404
|
+
inCall = false
|
|
405
|
+
mainHandler.removeCallbacks(callWatch)
|
|
406
|
+
mainHandler.postDelayed(callWatch, 500)
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
private fun stopCallWatch() {
|
|
410
|
+
mainHandler.removeCallbacks(callWatch)
|
|
411
|
+
if (inCall) {
|
|
412
|
+
inCall = false
|
|
413
|
+
sendEvent("onAudioInterruption", mapOf("reason" to "call_ended"))
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
}
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
package expo.modules.voicebot
|
|
2
|
+
|
|
3
|
+
import android.app.Notification
|
|
4
|
+
import android.app.NotificationChannel
|
|
5
|
+
import android.app.NotificationManager
|
|
6
|
+
import android.app.PendingIntent
|
|
7
|
+
import android.app.Service
|
|
8
|
+
import android.content.Context
|
|
9
|
+
import android.content.Intent
|
|
10
|
+
import android.content.pm.ServiceInfo
|
|
11
|
+
import android.os.Build
|
|
12
|
+
import android.os.IBinder
|
|
13
|
+
import android.util.Log
|
|
14
|
+
import androidx.core.content.ContextCompat
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Foreground service (type "microphone") that runs only while the voice bot mic is on.
|
|
18
|
+
*
|
|
19
|
+
* Android stops giving mic audio to apps in the background unless they run a foreground service
|
|
20
|
+
* of type microphone, which must show a notification. The recording itself stays in
|
|
21
|
+
* VoiceBotAudioModule; this service only keeps the app allowed to use the mic, so the voice bot
|
|
22
|
+
* keeps listening when the user switches apps or locks the screen.
|
|
23
|
+
*/
|
|
24
|
+
class VoiceBotMicService : Service() {
|
|
25
|
+
companion object {
|
|
26
|
+
private const val TAG = "VoiceBotAudio"
|
|
27
|
+
private const val CHANNEL_ID = "voicebot_mic"
|
|
28
|
+
private const val NOTIFICATION_ID = 0x7B07
|
|
29
|
+
private const val EXTRA_TITLE = "title"
|
|
30
|
+
private const val EXTRA_TEXT = "text"
|
|
31
|
+
|
|
32
|
+
/** Starts the service. Returns false if Android refused (e.g. the app is in the background). */
|
|
33
|
+
fun start(context: Context, title: String, text: String): Boolean {
|
|
34
|
+
val intent = Intent(context, VoiceBotMicService::class.java)
|
|
35
|
+
.putExtra(EXTRA_TITLE, title)
|
|
36
|
+
.putExtra(EXTRA_TEXT, text)
|
|
37
|
+
return try {
|
|
38
|
+
ContextCompat.startForegroundService(context, intent)
|
|
39
|
+
true
|
|
40
|
+
} catch (e: Exception) {
|
|
41
|
+
Log.w(TAG, "Background listening not available: ${e.message}")
|
|
42
|
+
false
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
fun stop(context: Context) {
|
|
47
|
+
try {
|
|
48
|
+
context.stopService(Intent(context, VoiceBotMicService::class.java))
|
|
49
|
+
} catch (e: Exception) {
|
|
50
|
+
Log.w(TAG, "stop service: ${e.message}")
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
override fun onBind(intent: Intent?): IBinder? = null
|
|
56
|
+
|
|
57
|
+
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
|
58
|
+
val title = intent?.getStringExtra(EXTRA_TITLE) ?: "Voice assistant"
|
|
59
|
+
val text = intent?.getStringExtra(EXTRA_TEXT) ?: "Listening"
|
|
60
|
+
val notification = buildNotification(title, text)
|
|
61
|
+
try {
|
|
62
|
+
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
|
63
|
+
startForeground(NOTIFICATION_ID, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE)
|
|
64
|
+
} else {
|
|
65
|
+
startForeground(NOTIFICATION_ID, notification)
|
|
66
|
+
}
|
|
67
|
+
Log.i(TAG, "Background listening on (foreground service started)")
|
|
68
|
+
} catch (e: Exception) {
|
|
69
|
+
Log.w(TAG, "Could not start foreground service: ${e.message}")
|
|
70
|
+
stopSelf()
|
|
71
|
+
}
|
|
72
|
+
return START_NOT_STICKY
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
override fun onDestroy() {
|
|
76
|
+
Log.i(TAG, "Background listening off (foreground service stopped)")
|
|
77
|
+
super.onDestroy()
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
private fun buildNotification(title: String, text: String): Notification {
|
|
81
|
+
val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
|
|
82
|
+
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && manager.getNotificationChannel(CHANNEL_ID) == null) {
|
|
83
|
+
manager.createNotificationChannel(
|
|
84
|
+
NotificationChannel(CHANNEL_ID, "Voice assistant", NotificationManager.IMPORTANCE_LOW).apply {
|
|
85
|
+
description = "Shown while the voice assistant is listening"
|
|
86
|
+
setShowBadge(false)
|
|
87
|
+
}
|
|
88
|
+
)
|
|
89
|
+
}
|
|
90
|
+
val open = packageManager.getLaunchIntentForPackage(packageName)?.let {
|
|
91
|
+
PendingIntent.getActivity(this, 0, it, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
|
|
92
|
+
}
|
|
93
|
+
val builder = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
|
94
|
+
Notification.Builder(this, CHANNEL_ID)
|
|
95
|
+
} else {
|
|
96
|
+
@Suppress("DEPRECATION") Notification.Builder(this)
|
|
97
|
+
}
|
|
98
|
+
return builder
|
|
99
|
+
.setContentTitle(title)
|
|
100
|
+
.setContentText(text)
|
|
101
|
+
.setSmallIcon(applicationInfo.icon.takeIf { it != 0 } ?: android.R.drawable.ic_btn_speak_now)
|
|
102
|
+
.setOngoing(true)
|
|
103
|
+
.setCategory(Notification.CATEGORY_SERVICE)
|
|
104
|
+
.apply { if (open != null) setContentIntent(open) }
|
|
105
|
+
.build()
|
|
106
|
+
}
|
|
107
|
+
}
|
package/app.plugin.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
module.exports = require('./plugin/withVoiceBot');
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/** focus_lost: another app took the audio. call_started / call_ended: a phone call (or Siri, alarm on iOS). */
|
|
2
|
+
export type InterruptionReason = 'focus_lost' | 'call_started' | 'call_ended';
|
|
3
|
+
export declare const NATIVE_MISSING_MESSAGE: string;
|
|
4
|
+
export declare function isNativeAvailable(): boolean;
|
|
5
|
+
export declare function getPackageName(): string;
|
|
6
|
+
/** Asks for the microphone permission if needed. Resolves to whether it is granted. */
|
|
7
|
+
export declare function requestMicPermission(): Promise<boolean>;
|
|
8
|
+
export declare function startRecording(onFrame: (base64: string) => void, onError: (msg: string) => void): Promise<() => void>;
|
|
9
|
+
export declare function stopRecording(): void;
|
|
10
|
+
/** Queues base64 PCM s16le mono audio played at `sampleRate` (default 16000). */
|
|
11
|
+
export declare function enqueuePlayback(base64: string, sampleRate?: number): void;
|
|
12
|
+
export declare function stopPlayback(): void;
|
|
13
|
+
/** A random id saved on the device, the same across app launches. `null` if not available. */
|
|
14
|
+
export declare function getPersistentId(key: string): string | null;
|
|
15
|
+
/**
|
|
16
|
+
* Android: starts the foreground service that keeps the mic working in the background (it shows a
|
|
17
|
+
* notification while listening). Returns false when not available (iOS, or Android refused).
|
|
18
|
+
*/
|
|
19
|
+
export declare function startBackgroundService(title: string, text: string): Promise<boolean>;
|
|
20
|
+
export declare function stopBackgroundService(): void;
|
|
21
|
+
/** Gives audio focus back so other apps play at full volume again. */
|
|
22
|
+
export declare function releaseAudioFocus(): void;
|
|
23
|
+
/** Calls, other apps taking the audio. Returns an unsubscribe function. */
|
|
24
|
+
export declare function onInterruption(listener: (reason: InterruptionReason) => void): () => void;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{requireOptionalNativeModule as e}from"expo-modules-core";import{PermissionsAndroid as t,Platform as r}from"react-native";const o=e("VoiceBotAudio");export const NATIVE_MISSING_MESSAGE="The VoiceBotAudio native module is not available. Expo Go cannot load it: use a development build (`npx expo run:android`) or rebuild your bare app after installing the package.";export function isNativeAvailable(){return null!=o}function n(){if(!o)throw new Error(NATIVE_MISSING_MESSAGE);return o}export function getPackageName(){try{return o?.getAppInfo().packageName??""}catch{return""}}export async function requestMicPermission(){const e=n();return!!e.hasPermission()||("android"===r.OS?await t.request(t.PERMISSIONS.RECORD_AUDIO)===t.RESULTS.GRANTED:!!e.requestPermission&&e.requestPermission())}export function startRecording(e,t){const r=n(),o=[r.addListener("onAudioFrame",(t=>e(t.data))),r.addListener("onAudioError",(e=>t(e.message)))],a=()=>o.forEach((e=>e.remove()));return r.startRecording().then((()=>a),(e=>{throw a(),e}))}export function stopRecording(){o?.stopRecording()}export function enqueuePlayback(e,t=16e3){n().enqueuePlayback(e,t)}export function stopPlayback(){o?.stopPlayback()}export function getPersistentId(e){try{return o?.getPersistentId?.(e)??null}catch{return null}}let a=!1;export async function startBackgroundService(e,n){if("android"!==r.OS||!o?.startBackgroundService)return!1;const i=t.PERMISSIONS.POST_NOTIFICATIONS;if(!a&&i&&Number(r.Version)>=33){a=!0;try{await t.check(i)||await t.request(i)}catch{}}try{return o.startBackgroundService(e,n)}catch{return!1}}export function stopBackgroundService(){try{o?.stopBackgroundService?.()}catch{}}export function releaseAudioFocus(){try{o?.releaseAudioFocus?.()}catch{}}export function onInterruption(e){if(!o)return()=>{};try{const t=o.addListener("onAudioInterruption",(t=>e(t.reason)));return()=>t.remove()}catch{return()=>{}}}
|