@picovoice/porcupine-react-native
Version:
Picovoice Porcupine React Native binding
162 lines (157 loc) • 9.07 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _reactNativeVoiceProcessor = require("@picovoice/react-native-voice-processor");
var _porcupine = _interopRequireDefault(require("./porcupine"));
var PorcupineErrors = _interopRequireWildcard(require("./porcupine_errors"));
function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); }
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } //
// Copyright 2020-2025 Picovoice Inc.
//
// You may not use this file except in compliance with the license. A copy of the license is located in the "LICENSE"
// file accompanying this source.
//
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
// an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
//
class PorcupineManager {
/**
* Static creator for initializing a Porcupine Manager from built-in keywords
*
* @param accessKey AccessKey obtained from Picovoice Console (https://console.picovoice.ai/).
* @param keywords List of keywords (phrases) for detection. The list of available (default) keywords can be retrieved.
* using `Porcupine.KEYWORDS`. If `keyword_paths` is set then this argument will be ignored.
* @param detectionCallback A callback for when Porcupine detects the specified keywords.
* @param processErrorCallback A callback for when Porcupine process function triggers an error.
* @param modelPath Path to the file containing model parameters. If not set it will be set to the default location.
* @param device String representation of the device (e.g., CPU or GPU) to use for inference.
* If set to `best`, the most suitable device is selected automatically. If set to `gpu`, the engine uses the
* first available GPU device. To select a specific GPU device, set this argument to `gpu:${GPU_INDEX}`, where
* `${GPU_INDEX}` is the index of the target GPU. If set to `cpu`, the engine will run on the CPU with the
* default number of threads. To specify the number of threads, set this argument to `cpu:${NUM_THREADS}`,
* where `${NUM_THREADS}` is the desired number of threads.
* @param sensitivities sensitivities for each keyword model. A higher sensitivity reduces miss rate
* at the cost of potentially higher false alarm rate. Sensitivity should be a floating-point number within
* [0, 1].
* @returns An instance of the Porcupine Manager.
*/
static async fromBuiltInKeywords(accessKey, keywords, detectionCallback, processErrorCallback, modelPath, device, sensitivities) {
let porcupine = await _porcupine.default.fromBuiltInKeywords(accessKey, keywords, modelPath, device, sensitivities);
return new PorcupineManager(porcupine, detectionCallback, processErrorCallback);
}
/**
* Static creator for initializing a Porcupine Manager from paths to custom keywords.
*
* @param accessKey AccessKey obtained from Picovoice Console (https://console.picovoice.ai/).
* @param keywordPaths Absolute paths to keyword model files.
* @param detectionCallback A callback for when Porcupine detects the specified keywords.
* @param processErrorCallback A callback for when Porcupine process function triggers an error.
* @param modelPath Path to the file containing model parameters. If not set it will be set to the default location.
* @param device String representation of the device (e.g., CPU or GPU) to use for inference.
* If set to `best`, the most suitable device is selected automatically. If set to `gpu`, the engine uses the
* first available GPU device. To select a specific GPU device, set this argument to `gpu:${GPU_INDEX}`, where
* `${GPU_INDEX}` is the index of the target GPU. If set to `cpu`, the engine will run on the CPU with the
* default number of threads. To specify the number of threads, set this argument to `cpu:${NUM_THREADS}`,
* where `${NUM_THREADS}` is the desired number of threads.
* @param sensitivities sensitivities for each keyword model. A higher sensitivity reduces miss rate
* at the cost of potentially higher false alarm rate. Sensitivity should be a floating-point number within
* [0, 1].
* @returns An instance of the Porcupine Manager.
*/
static async fromKeywordPaths(accessKey, keywordPaths, detectionCallback, processErrorCallback, modelPath, device, sensitivities) {
let porcupine = await _porcupine.default.fromKeywordPaths(accessKey, keywordPaths, modelPath, device, sensitivities);
return new PorcupineManager(porcupine, detectionCallback, processErrorCallback);
}
constructor(porcupine, detectionCallback, processErrorCallback) {
_defineProperty(this, "_voiceProcessor", void 0);
_defineProperty(this, "_errorListener", void 0);
_defineProperty(this, "_frameListener", void 0);
_defineProperty(this, "_porcupine", void 0);
_defineProperty(this, "_isListening", false);
this._porcupine = porcupine;
this._voiceProcessor = _reactNativeVoiceProcessor.VoiceProcessor.instance;
this._frameListener = async frame => {
if (this._porcupine === null || !this._isListening) {
return;
}
try {
let keywordIndex = await this._porcupine.process(frame);
if (keywordIndex >= 0) {
detectionCallback(keywordIndex);
}
} catch (e) {
if (processErrorCallback) {
processErrorCallback(e);
} else {
console.error(e);
}
}
};
this._errorListener = error => {
if (processErrorCallback) {
processErrorCallback(new PorcupineErrors.PorcupineError(error.message));
} else {
console.error(error);
}
};
}
/**
* Opens audio input stream and sends audio frames to Porcupine
*/
async start() {
if (this._isListening) {
return;
}
if (this._porcupine === null) {
throw new PorcupineErrors.PorcupineInvalidStateError('Cannot start Porcupine - resources have already been released');
}
if (await this._voiceProcessor.hasRecordAudioPermission()) {
this._voiceProcessor.addFrameListener(this._frameListener);
this._voiceProcessor.addErrorListener(this._errorListener);
try {
await this._voiceProcessor.start(this._porcupine.frameLength, this._porcupine.sampleRate);
} catch (e) {
throw new PorcupineErrors.PorcupineRuntimeError(`Failed to start audio recording: ${e.message}`);
}
} else {
throw new PorcupineErrors.PorcupineRuntimeError('User did not give permission to record audio.');
}
this._isListening = true;
}
/**
* Closes audio stream
*/
async stop() {
if (!this._isListening) {
return;
}
this._voiceProcessor.removeErrorListener(this._errorListener);
this._voiceProcessor.removeFrameListener(this._frameListener);
if (this._voiceProcessor.numFrameListeners === 0) {
try {
await this._voiceProcessor.stop();
} catch (e) {
throw new PorcupineErrors.PorcupineRuntimeError(`Failed to stop audio recording: ${e.message}`);
}
}
this._isListening = false;
}
/**
* Releases resources and listeners
*/
delete() {
if (this._porcupine !== null) {
this._porcupine.delete();
this._porcupine = null;
}
}
}
var _default = exports.default = PorcupineManager;
//# sourceMappingURL=porcupine_manager.js.map