npm package: @picovoice/porcupine-web
Description: Porcupine wake word engine for web browsers (via WebAssembly)
Author: Picovoice Inc
Latest version: 4.0.0

# Porcupine Binding for Web

## Porcupine wake word engine

Made in Vancouver, Canada by [Picovoice](https://picovoice.ai)

Porcupine is a highly accurate and lightweight wake word engine. It enables building always-listening voice-enabled
applications using cutting edge voice AI.

Porcupine is:

- private and offline
- [accurate](https://github.com/Picovoice/wake-word-benchmark)
- [resource efficient](https://www.youtube.com/watch?v=T0tAnh8tUQg) (runs even on microcontrollers)
- data efficient (wake words can be easily generated by simply typing them, without needing thousands of hours of
  bespoke audio training data and manual effort)
- scalable to many simultaneous wake-words / always-on voice commands
- cross-platform

## Compatibility

- Chrome / Edge
- Firefox
- Safari

## Requirements

The Porcupine Web Binding uses [SharedArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer).

Include the following headers in the response to enable the use of `SharedArrayBuffers`:

```
Cross-Origin-Opener-Policy: same-origin
Cross-Origin-Embedder-Policy: require-corp
```

Refer to our [Web demo](../../demo/web) for an example on creating a server with the corresponding response headers.

Browsers that don't support `SharedArrayBuffers` or applications that don't include the required headers will fall back to using standard `ArrayBuffers`. This will disable multithreaded processing.

### Restrictions

IndexedDB is required to use `Porcupine` in a worker thread. Browsers without IndexedDB support
(i.e. Firefox Incognito Mode) should use `Porcupine` in the main thread.

Multi-threading is only enabled for Porcupine when using on a web worker.

## Installation

### Package

Using `Yarn`:

```console
yarn add @picovoice/porcupine-web
```

or using `npm`:

```console
npm install --save @picovoice/porcupine-web
```

### AccessKey

Porcupine requires a valid Picovoice `AccessKey` at initialization. `AccessKey` acts as your credentials when using
Porcupine SDKs.
You can get your `AccessKey` for free. Make sure to keep your `AccessKey` secret.
Signup or Login to [Picovoice Console](https://console.picovoice.ai/) to get your `AccessKey`.

## Usage

There are two methods to pass model files and initialize Porcupine:

### Public Directory

**NOTE**: Due to modern browser limitations of using a file URL, this method does __not__ work if used without hosting a
server.

This method fetches [the model file](https://github.com/Picovoice/porcupine/blob/master/lib/common/porcupine_params.pv)
from the public directory and feeds it to Porcupine.
Copy the model file into the public directory:

```console
cp ${PORCUPINE_MODEL_FILE} ${PATH_TO_PUBLIC_DIRECTORY}
```

The same procedure can be used for the [custom keyword files](#custom-keywords) (`.ppn`) files.

### Base64

**NOTE**: This method works without hosting a server, but increases the size of the model file roughly by 33%.

This method uses a base64 string of the model file and feeds it to Porcupine. Use the built-in script `pvbase64` to
base64 your model file:

```console
npx pvbase64 -i ${MODEL_FILE} -o ${OUTPUT_DIRECTORY}/${MODEL_NAME}.js
```

The output will be a js file which you can import into any file of your project. For detailed information
about `pvbase64`, run:

```console
npx pvbase64 -h
```

The same procedure can be used for the [custom keyword files](#custom-keywords) (`.ppn`) files.

### Porcupine Model

Porcupine saves and caches your parameter model file (`.pv`) in IndexedDB to be used by Web Assembly.
Use a different `customWritePath` variable to hold multiple model values and set the `forceWrite` value to true to force
re-save the model file.
If the model file changes, `version` should be incremented to force the cached models to be updated.
Either `base64` or `publicPath` must be set to instantiate Porcupine. If both are set, Porcupine will use the `base64`
model.

```typescript
// Model (.pv)
const porcupineModel = {
  publicPath: ${MODEL_RELATIVE_PATH},
  // or
  base64: ${MODEL_BASE64_STRING},

  // Optional
  customWritePath: 'custom_model',
  forceWrite: true,
  version: 1,
}
```

### Initialize Porcupine

Create a `keywordDetectionCallback` function to get the results from the engine:

```typescript
function keywordDetectionCallback(keyword) {
  console.log(`Porcupine detected keyword: ${keyword.label}`);
}
```

create an `options` object and add a `processErrorCallback` function if you would like to catch errors:

```typescript
function processErrorCallback(error: string) {
...
}

options.processErrorCallback = processErrorCallback;
```

Initialize an instance of `Porcupine` in the main thread:

```typescript
const handle = await Porcupine.create(
  ${ACCESS_KEY},
  PorcupineWeb.BuiltInKeyword.Porcupine,
  keywordDetectionCallback,
  porcupineModel,
  options // optional options
);
```

or initialize an instance of `Porcupine` in a worker thread:

```typescript
const handle = await PorcupineWorker.create(
  ${ACCESS_KEY},
  PorcupineWeb.BuiltInKeyword.Porcupine,
  keywordDetectionCallback,
  porcupineModel,
  options // optional options
);
```

### Process Audio Frames

The result is received from `keywordDetectionCallback` as defined above.

```typescript
function getAudioData(): Int16Array {
... // function to get audio data
  return new Int16Array();
}

for (; ;) {
  await handle.process(getAudioData());
  // break on some condition
}
```

### Clean Up

Clean up used resources by `Porcupine` or `PorcupineWorker`:

```typescript
await handle.release();
```

### Terminate

Terminate `PorcupineWorker` instance:

```typescript
await handle.terminate();
```

## Custom Keywords

Create custom keywords using the [Picovoice Console](https://console.picovoice.ai/).
Train and download a Porcupine keyword model (`.ppn`) for the target platform `Web (WASM)`. 
This model file can be used directly with `publicPath`, but, if `base64` is preferable, convert the `.ppn` file to a base64 
JavaScript variable using the built-in `pvbase64` script:

```console
npx pvbase64 -i ${KEYWORD_FILE}.ppn -o ${KEYWORD_BASE64}.js -n ${KEYWORD_BASE64_VAR_NAME}
```

Similar to the model file (`.pv`), keyword files (`.ppn`) are saved in IndexedDB to be used by Web Assembly.
Either `base64` or `publicPath` must be set for each keyword to instantiate Porcupine. 
If both are set, Porcupine will use the `base64` model. 
An arbitrary `label` is required to identify the keyword once the detection occurs.

```typescript
// custom keyword (.ppn)
const keywordModel = {
  publicPath: ${KEYWORD_RELATIVE_PATH},
  // or
  base64: ${KEYWORD_BASE64_STRING},
  label: ${KEYWORD_LABEL},
  // Optional
  customWritePath: 'custom_keyword',
  forceWrite: true,
  version: 1,
}
```

Then, initialize an instance of `Porcupine`:

```typescript
const handle = await Porcupine.create(
  ${ACCESS_KEY},
  [keywordModel],
  keywordDetectionCallback,
  porcupineModel,
  options
);
```

## Non-English Languages

In order to detect non-English wake words you need to use the corresponding model file (`.pv`). The model files for all
supported languages are available [here](https://github.com/Picovoice/porcupine/tree/master/lib/common).

## Demo

For example usage refer to our [Web demo application](https://github.com/Picovoice/porcupine/tree/master/demo/web).