react-native-voice-bot-sdk 0.0.0-stage → 0.1.0
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 +49 -0
- package/LICENSE +21 -0
- package/README.md +464 -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
package/docs/PROTOCOL.md
ADDED
|
@@ -0,0 +1,271 @@
|
|
|
1
|
+
# Voice Bot – WebSocket protocol (React Native SDK)
|
|
2
|
+
|
|
3
|
+
This is the protocol the `react-native-voice-bot-sdk` client speaks. Audio, replies and
|
|
4
|
+
navigation are the **same as the native Android voice bot app** (`AUDIO_FORMAT.md` in that
|
|
5
|
+
project). The difference is the first message: session info and screen names are sent together in
|
|
6
|
+
**one connect message**. Differences are marked **RN** below.
|
|
7
|
+
|
|
8
|
+
Transport: one WebSocket connection per session, e.g. `ws://<host>:8091/demo`.
|
|
9
|
+
|
|
10
|
+
## Summary
|
|
11
|
+
|
|
12
|
+
| # | Direction | Frame | Content |
|
|
13
|
+
|---|-----------|-------|---------|
|
|
14
|
+
| 1 | App → Server | TEXT, once, first | Connect `{sessionId, domain_id, cookie_id, type:"Buffer", deviceId, sampleRate:16000, screens[]}` |
|
|
15
|
+
| 3 | App → Server | TEXT, right after 1 and on every screen change | `{type:"screen_changed", sessionId, screen, backStack[]}` |
|
|
16
|
+
| 4 | App → Server | BINARY stream | 640-byte frames of PCM s16le / 16 kHz / mono, in order, no gaps |
|
|
17
|
+
| 5 | Server → App | TEXT stream | Reply `{session_id, question, output{...}, buffer}`; `buffer` = base64 PCM s16le 16 kHz mono |
|
|
18
|
+
| 6 | Server → App | TEXT, any time | `{type:"navigate", screen, params?, requestId?}` or `{type:"navigate", action:"back"}` |
|
|
19
|
+
| 7 | App → Server | TEXT, answer to 6 | `{type:"navigate_result", sessionId, screen, action, className, status, message, requestId}` |
|
|
20
|
+
|
|
21
|
+
## 1. Connect message (App → Server, first TEXT frame) — **RN**
|
|
22
|
+
|
|
23
|
+
Sent once, right after the socket opens and before any audio. It has the session info **and** the
|
|
24
|
+
names of the app's UI screens in one JSON object:
|
|
25
|
+
|
|
26
|
+
```json
|
|
27
|
+
{
|
|
28
|
+
"sessionId": "c0a8f6e2-5b1d-4f0e-9d7a-2b6c1e3f4a5b",
|
|
29
|
+
"domain_id": "demo-domain",
|
|
30
|
+
"cookie_id": "9b2e4c1a-7f3d-4e8b-a1c6-5d0f2e9b7a34",
|
|
31
|
+
"type": "Buffer",
|
|
32
|
+
"deviceId": 1,
|
|
33
|
+
"sampleRate": 16000,
|
|
34
|
+
"screens": ["cart", "index", "product/[id]", "products", "profile"]
|
|
35
|
+
}
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
| Field | Meaning |
|
|
39
|
+
|-------|---------|
|
|
40
|
+
| `sessionId` | Random UUID v4, new for every connection. |
|
|
41
|
+
| `domain_id` | The host app's domain / tenant id, from `connect({ domainId })`. `""` if not set. |
|
|
42
|
+
| `cookie_id` | Visitor id, from `connect({ cookieId })`. If the app doesn't pass one, a random UUID saved on the device: the same across app launches until the app is uninstalled or its data is cleared. |
|
|
43
|
+
| `type` | Always `"Buffer"`. |
|
|
44
|
+
| `deviceId` | Default `1`; the app may override it. |
|
|
45
|
+
| `sampleRate` | Always `16000` (uplink and reply audio). |
|
|
46
|
+
| `screens` | **Array of strings**: the app's screen (route) names, sorted. Use one of these as `screen` in `navigate`. Empty array if the app didn't register navigation. |
|
|
47
|
+
|
|
48
|
+
Server side, read it like this:
|
|
49
|
+
|
|
50
|
+
```python
|
|
51
|
+
msg = json.loads(first_text_frame)
|
|
52
|
+
session_id = msg["sessionId"]
|
|
53
|
+
pages = msg["screens"] # ['cart', 'index', 'product/[id]', 'products', 'profile']
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
Only the **names of UI screens** are sent (Expo Router routes or React Navigation screen names).
|
|
57
|
+
No source code, data, helper or component names are ever sent.
|
|
58
|
+
|
|
59
|
+
Screen name formats:
|
|
60
|
+
|
|
61
|
+
- **Expo Router:** the file path under `app/` without extension: `index`, `products`, `(tabs)/index`,
|
|
62
|
+
`settings/profile`, `product/[id]`. Layouts (`_layout`), `+not-found`, `+html` and other internal
|
|
63
|
+
routes are left out.
|
|
64
|
+
- **React Navigation:** the screen names given to `<Stack.Screen name="...">`, e.g. `Home`, `ProductDetails`.
|
|
65
|
+
- **Custom:** whatever names the host app registered.
|
|
66
|
+
|
|
67
|
+
### 2. Screens update (rare)
|
|
68
|
+
|
|
69
|
+
Only if the app registers a different navigation while the session is already open, and the list
|
|
70
|
+
changed, the app sends the new list. A normal session never sends this:
|
|
71
|
+
|
|
72
|
+
```json
|
|
73
|
+
{ "type": "screens", "sessionId": "...", "screens": ["cart", "index", "products"] }
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
Replace the stored list with this one.
|
|
77
|
+
|
|
78
|
+
## 3. Screen changed + back stack (App → Server, TEXT)
|
|
79
|
+
|
|
80
|
+
Same as Android. Sent right after the connect message (the starting screen) and then every time a
|
|
81
|
+
different screen comes to the front: after a voice command, a tap, or the Back button.
|
|
82
|
+
|
|
83
|
+
```json
|
|
84
|
+
{
|
|
85
|
+
"type": "screen_changed",
|
|
86
|
+
"sessionId": "...",
|
|
87
|
+
"screen": "products",
|
|
88
|
+
"backStack": ["index", "products"]
|
|
89
|
+
}
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
`backStack` is ordered **bottom → top**; the last item is the visible screen. For tab navigators only
|
|
93
|
+
the focused tab is listed (tabs have no back stack). A stack inside a tab is listed in full.
|
|
94
|
+
|
|
95
|
+
## 4. Uplink audio (App → Server, BINARY frames)
|
|
96
|
+
|
|
97
|
+
Unchanged from Android:
|
|
98
|
+
|
|
99
|
+
| Property | Value |
|
|
100
|
+
|----------|-------|
|
|
101
|
+
| Encoding | Raw PCM, **signed 16-bit little-endian** (`s16le`) |
|
|
102
|
+
| Sample rate | **16000 Hz** |
|
|
103
|
+
| Channels | **1 (mono)** |
|
|
104
|
+
| Container | None (no WAV header) |
|
|
105
|
+
| Frame size | **640 bytes** = 320 samples = **20 ms** |
|
|
106
|
+
| Frame rate | ~50 frames/s (~32 KB/s) |
|
|
107
|
+
| Mic | Android: `VOICE_COMMUNICATION` source with echo cancel, gain control and noise suppression. iOS: voice-processing I/O. |
|
|
108
|
+
|
|
109
|
+
Each BINARY message is exactly one 640-byte frame. By default the app's noise gate replaces room
|
|
110
|
+
noise between sentences with **digital silence** (all-zero frames), so a simple energy or VAD check on
|
|
111
|
+
the server sees clean pauses. Frames keep coming every 20 ms; the stream runs 300 ms behind real time.
|
|
112
|
+
During a phone call the app also sends silence. Frames are sent strictly in recording order, with no
|
|
113
|
+
gaps. The mic keeps streaming while reply audio plays and while navigating.
|
|
114
|
+
|
|
115
|
+
Test a capture with `ffplay -f s16le -ar 16000 -ch_layout mono capture.raw`.
|
|
116
|
+
|
|
117
|
+
### 4b. Optional: base64 TEXT uplink — **RN, opt-in**
|
|
118
|
+
|
|
119
|
+
Only if the host app sets `uplinkEncoding: 'base64'` (the default is binary, above). Each 640-byte
|
|
120
|
+
frame is sent as a TEXT frame instead:
|
|
121
|
+
|
|
122
|
+
```json
|
|
123
|
+
{ "type": "audio", "sessionId": "...", "seq": 0, "sampleRate": 16000, "data": "<base64 of 640 bytes>" }
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
`seq` starts at 0 each time the mic starts and goes up by one per frame. **The server needs a change to
|
|
127
|
+
accept this format**, so leave the default unless the server team has added it.
|
|
128
|
+
|
|
129
|
+
## 5. Server reply (Server → App, TEXT)
|
|
130
|
+
|
|
131
|
+
Same as Android:
|
|
132
|
+
|
|
133
|
+
```json
|
|
134
|
+
{
|
|
135
|
+
"session_id": "c0a8f6e2-...",
|
|
136
|
+
"question": "what the user said",
|
|
137
|
+
"output": { "suggestions": ["..."], "prompt": "bot reply text", "intent": "...", "message": "...", "error": 0 },
|
|
138
|
+
"buffer": "<base64 audio>",
|
|
139
|
+
"sample_rate": 24000
|
|
140
|
+
}
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
- `buffer` = base64 of **raw PCM s16le, mono, no header**, at `sample_rate`.
|
|
144
|
+
- `sample_rate` (optional, top level): the sample rate of `buffer` in Hz, 8000–48000, e.g. `24000`.
|
|
145
|
+
Missing = `16000`. **It must match the audio**: 24 kHz audio labelled (or defaulted to) 16 kHz plays
|
|
146
|
+
1.5× too slow and too deep. Chunks are played in the order
|
|
147
|
+
received. Send `"buffer": ""` for text-only messages. Each chunk should have an even number of bytes.
|
|
148
|
+
- Messages with the same `question` are parts of one reply and play one after the other. When a
|
|
149
|
+
reply with a **different** `question` (and audio) arrives while older audio is still playing, the
|
|
150
|
+
app stops the old audio and plays the new reply right away. So keep `question` the same in every
|
|
151
|
+
chunk of one reply.
|
|
152
|
+
- `output` may be an object or a JSON-encoded string.
|
|
153
|
+
- The SDK is more lenient than the Android app: a message with missing keys is **not** dropped. It
|
|
154
|
+
plays `buffer` if present and passes the whole message to the app.
|
|
155
|
+
|
|
156
|
+
### 5b. Navigation inside a reply — **RN**
|
|
157
|
+
|
|
158
|
+
The server opens a screen by putting it in the reply's `output`:
|
|
159
|
+
|
|
160
|
+
```json
|
|
161
|
+
{
|
|
162
|
+
"session_id": "...",
|
|
163
|
+
"question": "go back",
|
|
164
|
+
"output": {
|
|
165
|
+
"prompt": "Going back to the home page.",
|
|
166
|
+
"message": "Going back to the home page.",
|
|
167
|
+
"intent": "navigate",
|
|
168
|
+
"type": "navigation",
|
|
169
|
+
"screen": "index",
|
|
170
|
+
"class_name": "index",
|
|
171
|
+
"target": "index",
|
|
172
|
+
"suggestions": [],
|
|
173
|
+
"error": 0
|
|
174
|
+
},
|
|
175
|
+
"buffer": "<base64 PCM>"
|
|
176
|
+
}
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
| Field | Value |
|
|
180
|
+
|-------|-------|
|
|
181
|
+
| `output.type` | `"navigation"` to open a screen, `"none"` otherwise. |
|
|
182
|
+
| `output.screen` | One of the `screens` names (or `"back"` to go back). `""` = no navigation. |
|
|
183
|
+
| `output.class_name`, `output.target` | Same name; older fields, used only when `screen` is empty. |
|
|
184
|
+
| `output.intent` | `"navigate"` for navigation replies (informational). |
|
|
185
|
+
|
|
186
|
+
The app takes the first non-empty of `screen`, `class_name`, `target`, opens it with the same
|
|
187
|
+
matching and back stack rules as `navigate` (section 6), and answers with `navigate_result` (no
|
|
188
|
+
`requestId`). If `type` isn't `"navigation"` (and `intent` isn't `"navigate"`), the name is used only
|
|
189
|
+
when it is exactly one of the app's screens. A reply split over several chunks navigates only once (same screen within 3 s); the same request later navigates again.
|
|
190
|
+
|
|
191
|
+
## 6. Navigate (Server → App, TEXT)
|
|
192
|
+
|
|
193
|
+
```json
|
|
194
|
+
{ "type": "navigate", "screen": "products", "requestId": 1 }
|
|
195
|
+
{ "type": "navigate", "screen": "product/[id]", "params": { "id": "7" }, "requestId": 2 }
|
|
196
|
+
{ "type": "navigate", "action": "back", "requestId": 3 }
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
- `screen` is matched in this order:
|
|
200
|
+
1. an exact name from `screens` (or its URL path, e.g. `/products`);
|
|
201
|
+
2. the same, case-insensitive (`Products`, `/products`);
|
|
202
|
+
3. the last part of the name, if exactly one screen has it (`profile` for `settings/profile`; a trailing
|
|
203
|
+
`Screen` is ignored, so `ProfileScreen` also matches).
|
|
204
|
+
- Only screens from the `screens` list can be opened; anything else returns `unknown_screen`.
|
|
205
|
+
- `params` (**RN**, optional): route params, e.g. for dynamic routes like `product/[id]`.
|
|
206
|
+
- `requestId` is optional and echoed back.
|
|
207
|
+
- Can be sent any time while the socket is open; audio keeps streaming.
|
|
208
|
+
|
|
209
|
+
### Back stack rules (same as Android)
|
|
210
|
+
|
|
211
|
+
| Command | Result | Example (bottom → top) |
|
|
212
|
+
|---------|--------|------------------------|
|
|
213
|
+
| Open a screen that isn't in the stack | Pushed on top. | `index` → open products → `index, products` |
|
|
214
|
+
| Open a screen that's already in the stack | Screens above it are removed; the existing screen is reused with its state. | `index, products, cart` → open products → `index, products` |
|
|
215
|
+
| Open the visible screen (no `params`) | Nothing happens; `already_on_screen`. | |
|
|
216
|
+
| `back` | Like the Back button. | `index, products` → back → `index` |
|
|
217
|
+
|
|
218
|
+
The SDK never closes the app: `back` on the first screen returns `not_supported` ("Nothing to go back to").
|
|
219
|
+
|
|
220
|
+
## 7. Navigate result (App → Server, TEXT)
|
|
221
|
+
|
|
222
|
+
```json
|
|
223
|
+
{
|
|
224
|
+
"type": "navigate_result",
|
|
225
|
+
"sessionId": "...",
|
|
226
|
+
"screen": "products",
|
|
227
|
+
"action": "open",
|
|
228
|
+
"className": "products",
|
|
229
|
+
"status": "opened",
|
|
230
|
+
"message": "",
|
|
231
|
+
"requestId": 1
|
|
232
|
+
}
|
|
233
|
+
```
|
|
234
|
+
|
|
235
|
+
`className` keeps the Android field name; for RN it holds the **full route name** that was acted on.
|
|
236
|
+
|
|
237
|
+
| `status` | Meaning |
|
|
238
|
+
|----------|---------|
|
|
239
|
+
| `opened` | The screen was pushed, or popped back to. |
|
|
240
|
+
| `went_back` | `back` was performed (`className` = the screen it went back from). |
|
|
241
|
+
| `already_on_screen` | The user is already on that screen. |
|
|
242
|
+
| `unknown_screen` | Not in the `screens` list (`className` is `null`). |
|
|
243
|
+
| `not_supported` | Nothing to go back to, or the app didn't register navigation with the SDK. |
|
|
244
|
+
| `failed` | The navigation call threw; the reason is in `message`. |
|
|
245
|
+
|
|
246
|
+
## 8. Example session
|
|
247
|
+
|
|
248
|
+
```
|
|
249
|
+
→ (open) ← connect {…, screens[…]} ← screen_changed [index]
|
|
250
|
+
→ navigate products ← opened ← screen_changed [index, products]
|
|
251
|
+
→ navigate cart ← opened ← screen_changed [index, products, cart]
|
|
252
|
+
→ navigate products ← opened ← screen_changed [index, products]
|
|
253
|
+
→ navigate products ← already_on_screen
|
|
254
|
+
→ navigate back ← went_back ← screen_changed [index]
|
|
255
|
+
→ navigate product/[id] {id:7} ← opened ← screen_changed [index, product/[id]]
|
|
256
|
+
→ navigate DoesNotExist ← unknown_screen
|
|
257
|
+
```
|
|
258
|
+
|
|
259
|
+
## 9. Reconnects
|
|
260
|
+
|
|
261
|
+
If the connection drops, the app reconnects by itself (1 s, 2 s, 4 s … 30 s apart). Each reconnect is
|
|
262
|
+
a **new session** by default: a new `sessionId`, and the connect message (with the same `cookie_id` and
|
|
263
|
+
`screens`) and `screen_changed` are sent again. Audio continues on the new socket; audio recorded
|
|
264
|
+
while offline is not sent. If the server closes the socket with code `1000`, the app does not
|
|
265
|
+
reconnect. Apps can set `keepSessionOnReconnect: true` to reuse the previous `sessionId` (tell the
|
|
266
|
+
app team which one you want).
|
|
267
|
+
|
|
268
|
+
## 10. Closing
|
|
269
|
+
|
|
270
|
+
The app closes the socket with code `1000` and reason `"User exited"` when the host calls
|
|
271
|
+
`disconnect()` or the provider unmounts.
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
require 'json'
|
|
2
|
+
|
|
3
|
+
package = JSON.parse(File.read(File.join(__dir__, '..', 'package.json')))
|
|
4
|
+
|
|
5
|
+
Pod::Spec.new do |s|
|
|
6
|
+
s.name = 'VoiceBotAudio'
|
|
7
|
+
s.version = package['version']
|
|
8
|
+
s.summary = package['description']
|
|
9
|
+
s.description = package['description']
|
|
10
|
+
s.license = package['license']
|
|
11
|
+
s.author = package['author']
|
|
12
|
+
s.homepage = package['homepage']
|
|
13
|
+
s.platforms = { :ios => '16.4' }
|
|
14
|
+
s.swift_version = '5.9'
|
|
15
|
+
s.source = { git: '' }
|
|
16
|
+
s.static_framework = true
|
|
17
|
+
|
|
18
|
+
s.dependency 'ExpoModulesCore'
|
|
19
|
+
|
|
20
|
+
s.source_files = "**/*.{h,m,swift}"
|
|
21
|
+
s.pod_target_xcconfig = {
|
|
22
|
+
'DEFINES_MODULE' => 'YES',
|
|
23
|
+
'SWIFT_COMPILATION_MODE' => 'wholemodule'
|
|
24
|
+
}
|
|
25
|
+
end
|
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
import AVFoundation
|
|
2
|
+
import ExpoModulesCore
|
|
3
|
+
|
|
4
|
+
/// Raw PCM mic capture and playback for the voice bot SDK (iOS).
|
|
5
|
+
///
|
|
6
|
+
/// Capture: the input node is converted to PCM s16le, 16 kHz, mono and cut into exactly
|
|
7
|
+
/// 640-byte (20 ms) frames, emitted in order as `onAudioFrame` events.
|
|
8
|
+
/// Playback: base64 PCM s16le 16 kHz mono chunks are scheduled in order on a player node.
|
|
9
|
+
///
|
|
10
|
+
/// NOTE: iOS support is a first version and has not been tested on a device yet.
|
|
11
|
+
public class VoiceBotAudioModule: Module {
|
|
12
|
+
private static let sampleRate: Double = 16000
|
|
13
|
+
private static let frameBytes = 640
|
|
14
|
+
|
|
15
|
+
private let engine = AVAudioEngine()
|
|
16
|
+
private let player = AVAudioPlayerNode()
|
|
17
|
+
private var converter: AVAudioConverter?
|
|
18
|
+
private var pending = Data()
|
|
19
|
+
private var recording = false
|
|
20
|
+
private var playerAttached = false
|
|
21
|
+
private let queue = DispatchQueue(label: "voicebot.audio")
|
|
22
|
+
|
|
23
|
+
private lazy var pcmFormat: AVAudioFormat = AVAudioFormat(
|
|
24
|
+
commonFormat: .pcmFormatInt16, sampleRate: Self.sampleRate, channels: 1, interleaved: true)!
|
|
25
|
+
private lazy var floatFormat: AVAudioFormat = AVAudioFormat(
|
|
26
|
+
commonFormat: .pcmFormatFloat32, sampleRate: Self.sampleRate, channels: 1, interleaved: false)!
|
|
27
|
+
|
|
28
|
+
public func definition() -> ModuleDefinition {
|
|
29
|
+
Name("VoiceBotAudio")
|
|
30
|
+
|
|
31
|
+
Events("onAudioFrame", "onAudioError", "onAudioInterruption")
|
|
32
|
+
|
|
33
|
+
Constants([
|
|
34
|
+
"sampleRate": Int(Self.sampleRate),
|
|
35
|
+
"frameBytes": Self.frameBytes,
|
|
36
|
+
])
|
|
37
|
+
|
|
38
|
+
// A random id saved on the device (UserDefaults), the same across app launches.
|
|
39
|
+
Function("getPersistentId") { (key: String) -> String in
|
|
40
|
+
let defaultsKey = "expo.modules.voicebot.\(key)"
|
|
41
|
+
if let id = UserDefaults.standard.string(forKey: defaultsKey) { return id }
|
|
42
|
+
let id = UUID().uuidString.lowercased()
|
|
43
|
+
UserDefaults.standard.set(id, forKey: defaultsKey)
|
|
44
|
+
return id
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
Function("getAppInfo") { () -> [String: String] in
|
|
48
|
+
["packageName": Bundle.main.bundleIdentifier ?? ""]
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
Function("hasPermission") { () -> Bool in
|
|
52
|
+
AVAudioSession.sharedInstance().recordPermission == .granted
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
AsyncFunction("requestPermission") { (promise: Promise) in
|
|
56
|
+
AVAudioSession.sharedInstance().requestRecordPermission { granted in
|
|
57
|
+
promise.resolve(granted)
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
AsyncFunction("startRecording") {
|
|
62
|
+
try self.startRecording()
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
Function("stopRecording") {
|
|
66
|
+
self.stopRecording()
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
Function("isRecording") { () -> Bool in
|
|
70
|
+
self.recording
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// base64 PCM s16le mono; rate = its sample rate (8000-48000), default 16000.
|
|
74
|
+
Function("enqueuePlayback") { (base64: String, rate: Int?) in
|
|
75
|
+
self.enqueuePlayback(base64, rate: rate ?? Int(Self.sampleRate))
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
Function("stopPlayback") {
|
|
79
|
+
self.player.stop()
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// Phone calls, Siri, alarms: the audio session is interrupted.
|
|
83
|
+
OnCreate {
|
|
84
|
+
NotificationCenter.default.addObserver(
|
|
85
|
+
forName: AVAudioSession.interruptionNotification, object: nil, queue: .main
|
|
86
|
+
) { [weak self] note in
|
|
87
|
+
guard let self = self,
|
|
88
|
+
let raw = note.userInfo?[AVAudioSessionInterruptionTypeKey] as? UInt,
|
|
89
|
+
let type = AVAudioSession.InterruptionType(rawValue: raw) else { return }
|
|
90
|
+
if type == .began {
|
|
91
|
+
self.player.stop()
|
|
92
|
+
self.sendEvent("onAudioInterruption", ["reason": "call_started"])
|
|
93
|
+
} else {
|
|
94
|
+
try? AVAudioSession.sharedInstance().setActive(true)
|
|
95
|
+
if !self.engine.isRunning { try? self.engine.start() }
|
|
96
|
+
self.sendEvent("onAudioInterruption", ["reason": "call_ended"])
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// Nothing to release on iOS: the audio session stays active while the module is in use.
|
|
102
|
+
Function("releaseAudioFocus") {}
|
|
103
|
+
|
|
104
|
+
OnDestroy {
|
|
105
|
+
self.stopRecording()
|
|
106
|
+
self.player.stop()
|
|
107
|
+
self.engine.stop()
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
private func configureSession() throws {
|
|
112
|
+
let session = AVAudioSession.sharedInstance()
|
|
113
|
+
try session.setCategory(.playAndRecord, mode: .voiceChat, options: [.defaultToSpeaker, .allowBluetooth])
|
|
114
|
+
try session.setPreferredSampleRate(Self.sampleRate)
|
|
115
|
+
try session.setActive(true)
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
private func attachPlayerIfNeeded() {
|
|
119
|
+
if playerAttached { return }
|
|
120
|
+
engine.attach(player)
|
|
121
|
+
engine.connect(player, to: engine.mainMixerNode, format: playbackFormat)
|
|
122
|
+
playerAttached = true
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** Format of the reply audio being played; reconnects the player when the rate changes. */
|
|
126
|
+
private lazy var playbackFormat: AVAudioFormat = floatFormat
|
|
127
|
+
|
|
128
|
+
private func usePlaybackRate(_ rate: Double) {
|
|
129
|
+
if playbackFormat.sampleRate == rate { return }
|
|
130
|
+
guard let f = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: rate, channels: 1, interleaved: false) else { return }
|
|
131
|
+
playbackFormat = f
|
|
132
|
+
if playerAttached {
|
|
133
|
+
player.stop()
|
|
134
|
+
engine.disconnectNodeOutput(player)
|
|
135
|
+
engine.connect(player, to: engine.mainMixerNode, format: f)
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
private func startRecording() throws {
|
|
140
|
+
if recording { return }
|
|
141
|
+
guard AVAudioSession.sharedInstance().recordPermission == .granted else {
|
|
142
|
+
throw Exception(name: "ERR_MIC_PERMISSION", description: "Microphone permission not granted")
|
|
143
|
+
}
|
|
144
|
+
try configureSession()
|
|
145
|
+
let input = engine.inputNode
|
|
146
|
+
try? input.setVoiceProcessingEnabled(true) // echo cancellation, AGC, noise suppression
|
|
147
|
+
let inFormat = input.outputFormat(forBus: 0)
|
|
148
|
+
converter = AVAudioConverter(from: inFormat, to: pcmFormat)
|
|
149
|
+
pending = Data()
|
|
150
|
+
|
|
151
|
+
input.installTap(onBus: 0, bufferSize: 1024, format: inFormat) { [weak self] buffer, _ in
|
|
152
|
+
self?.handleInput(buffer)
|
|
153
|
+
}
|
|
154
|
+
attachPlayerIfNeeded()
|
|
155
|
+
if !engine.isRunning { try engine.start() }
|
|
156
|
+
recording = true
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
private func handleInput(_ buffer: AVAudioPCMBuffer) {
|
|
160
|
+
guard let converter = converter else { return }
|
|
161
|
+
let ratio = Self.sampleRate / buffer.format.sampleRate
|
|
162
|
+
let capacity = AVAudioFrameCount(Double(buffer.frameLength) * ratio) + 32
|
|
163
|
+
guard let out = AVAudioPCMBuffer(pcmFormat: pcmFormat, frameCapacity: capacity) else { return }
|
|
164
|
+
var consumed = false
|
|
165
|
+
var error: NSError?
|
|
166
|
+
converter.convert(to: out, error: &error) { _, status in
|
|
167
|
+
if consumed {
|
|
168
|
+
status.pointee = .noDataNow
|
|
169
|
+
return nil
|
|
170
|
+
}
|
|
171
|
+
consumed = true
|
|
172
|
+
status.pointee = .haveData
|
|
173
|
+
return buffer
|
|
174
|
+
}
|
|
175
|
+
if let error = error {
|
|
176
|
+
sendEvent("onAudioError", ["message": error.localizedDescription])
|
|
177
|
+
return
|
|
178
|
+
}
|
|
179
|
+
guard let ch = out.int16ChannelData else { return }
|
|
180
|
+
let bytes = Data(bytes: ch[0], count: Int(out.frameLength) * 2)
|
|
181
|
+
queue.async {
|
|
182
|
+
self.pending.append(bytes)
|
|
183
|
+
while self.pending.count >= Self.frameBytes {
|
|
184
|
+
let frame = self.pending.prefix(Self.frameBytes)
|
|
185
|
+
self.pending.removeFirst(Self.frameBytes)
|
|
186
|
+
self.sendEvent("onAudioFrame", ["data": Data(frame).base64EncodedString()])
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
private func stopRecording() {
|
|
192
|
+
if !recording { return }
|
|
193
|
+
recording = false
|
|
194
|
+
engine.inputNode.removeTap(onBus: 0)
|
|
195
|
+
queue.async { self.pending = Data() }
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
private func enqueuePlayback(_ base64: String, rate: Int) {
|
|
199
|
+
guard let data = Data(base64Encoded: base64), data.count >= 2 else { return }
|
|
200
|
+
usePlaybackRate(Double((8000...48000).contains(rate) ? rate : Int(Self.sampleRate)))
|
|
201
|
+
let frames = data.count / 2
|
|
202
|
+
guard let buf = AVAudioPCMBuffer(pcmFormat: playbackFormat, frameCapacity: AVAudioFrameCount(frames)) else { return }
|
|
203
|
+
buf.frameLength = AVAudioFrameCount(frames)
|
|
204
|
+
data.withUnsafeBytes { (raw: UnsafeRawBufferPointer) in
|
|
205
|
+
let src = raw.bindMemory(to: Int16.self)
|
|
206
|
+
let dst = buf.floatChannelData![0]
|
|
207
|
+
for i in 0..<frames { dst[i] = Float(Int16(littleEndian: src[i])) / 32768.0 }
|
|
208
|
+
}
|
|
209
|
+
do {
|
|
210
|
+
if !recording { try configureSession() }
|
|
211
|
+
attachPlayerIfNeeded()
|
|
212
|
+
if !engine.isRunning { try engine.start() }
|
|
213
|
+
player.scheduleBuffer(buf, completionHandler: nil)
|
|
214
|
+
if !player.isPlaying { player.play() }
|
|
215
|
+
} catch {
|
|
216
|
+
sendEvent("onAudioError", ["message": "Playback failed: \(error.localizedDescription)"])
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,78 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "react-native-voice-bot-sdk",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Drop-in voice assistant widget for React Native and Expo apps: talks to your voice server over a WebSocket, plays the spoken reply, and lets the server open screens in your app.",
|
|
5
|
+
"main": "build/index.js",
|
|
6
|
+
"types": "build/index.d.ts",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": {
|
|
9
|
+
"types": "./build/index.d.ts",
|
|
10
|
+
"default": "./build/index.js"
|
|
11
|
+
},
|
|
12
|
+
"./expo-router": {
|
|
13
|
+
"types": "./build/expo-router.d.ts",
|
|
14
|
+
"default": "./build/expo-router.js"
|
|
15
|
+
},
|
|
16
|
+
"./app.plugin.js": "./app.plugin.js",
|
|
17
|
+
"./package.json": "./package.json"
|
|
18
|
+
},
|
|
19
|
+
"files": [
|
|
20
|
+
"build",
|
|
21
|
+
"plugin",
|
|
22
|
+
"app.plugin.js",
|
|
23
|
+
"expo-module.config.json",
|
|
24
|
+
"android/build.gradle",
|
|
25
|
+
"android/src",
|
|
26
|
+
"ios",
|
|
27
|
+
"README.md",
|
|
28
|
+
"LICENSE",
|
|
29
|
+
"docs/PROTOCOL.md",
|
|
30
|
+
"docs/INTEGRATION.md",
|
|
31
|
+
"CHANGELOG.md",
|
|
32
|
+
"!build/**/*.map"
|
|
33
|
+
],
|
|
34
|
+
"scripts": {
|
|
35
|
+
"build": "rm -rf build && tsc -p tsconfig.build.json",
|
|
36
|
+
"typecheck": "tsc -p tsconfig.json --noEmit",
|
|
37
|
+
"test": "npm run build && node --experimental-detect-module --test test/",
|
|
38
|
+
"prepack": "npm run build:release",
|
|
39
|
+
"build:release": "npm run build && node scripts/minify-build.mjs"
|
|
40
|
+
},
|
|
41
|
+
"keywords": [
|
|
42
|
+
"ai-bot",
|
|
43
|
+
"assistant",
|
|
44
|
+
"expo",
|
|
45
|
+
"expo-router",
|
|
46
|
+
"navigation",
|
|
47
|
+
"pcm",
|
|
48
|
+
"react-native",
|
|
49
|
+
"react-navigation",
|
|
50
|
+
"speech",
|
|
51
|
+
"voice",
|
|
52
|
+
"voice-assistant",
|
|
53
|
+
"voice-bot",
|
|
54
|
+
"websocket",
|
|
55
|
+
"widget"
|
|
56
|
+
],
|
|
57
|
+
"license": "MIT",
|
|
58
|
+
"author": "",
|
|
59
|
+
"homepage": "",
|
|
60
|
+
"peerDependencies": {
|
|
61
|
+
"expo": ">=52.0.0",
|
|
62
|
+
"expo-router": "*",
|
|
63
|
+
"react": "*",
|
|
64
|
+
"react-native": "*"
|
|
65
|
+
},
|
|
66
|
+
"peerDependenciesMeta": {
|
|
67
|
+
"expo-router": {
|
|
68
|
+
"optional": true
|
|
69
|
+
}
|
|
70
|
+
},
|
|
71
|
+
"devDependencies": {
|
|
72
|
+
"terser": "^5.36.0",
|
|
73
|
+
"typescript": "~6.0.3"
|
|
74
|
+
},
|
|
75
|
+
"publishConfig": {
|
|
76
|
+
"access": "public"
|
|
77
|
+
}
|
|
78
|
+
}
|