### Install Cobra Web Demo with NPM Source: https://github.com/picovoice/cobra/blob/main/demo/web/README.md Installs project dependencies using npm. Run this before starting the local web server. ```console npm install ``` -------------------------------- ### Install Cobra Web Demo with Yarn Source: https://github.com/picovoice/cobra/blob/main/demo/web/README.md Installs project dependencies using Yarn. Run this before starting the local web server. ```console yarn ``` -------------------------------- ### Install Web Cobra Demo Dependencies Source: https://github.com/picovoice/cobra/blob/main/README.md Install dependencies for the web demo of Cobra using either Yarn or npm. After installation, run the start script to launch the demo server. ```console yarn yarn start ``` ```console npm install npm run start ``` -------------------------------- ### Start Cobra Web Demo Server with NPM Source: https://github.com/picovoice/cobra/blob/main/demo/web/README.md Starts a local web server to host the Cobra demo. Access the demo via http://localhost:5000. ```console npm run start ``` -------------------------------- ### Install Cobra Node.js Demo Source: https://github.com/picovoice/cobra/blob/main/demo/nodejs/README.md Installs the Cobra Node.js demo package globally. Ensure Node.js 18+ is installed. ```console npm install -g @picovoice/cobra-node-demo ``` -------------------------------- ### Start Cobra Web Demo Server with Yarn Source: https://github.com/picovoice/cobra/blob/main/demo/web/README.md Starts a local web server to host the Cobra demo. Access the demo via http://localhost:5000. ```console yarn start ``` -------------------------------- ### Install NodeJS Cobra Demo Source: https://github.com/picovoice/cobra/blob/main/README.md Install the NodeJS demo package globally using yarn. ```bash yarn global add @picovoice/cobra-node-demo ``` -------------------------------- ### Install Cobra Web Binding Source: https://github.com/picovoice/cobra/blob/main/binding/web/README.md Install the Cobra web binding package using either yarn or npm. ```bash yarn add @picovoice/cobra-web ``` ```bash npm install --save @picovoice/cobra-web ``` -------------------------------- ### Install Cobra Node.js Binding Source: https://github.com/picovoice/cobra/blob/main/binding/nodejs/README.md Install the Cobra Node.js package using npm. ```bash npm install @picovoice/cobra-node ``` -------------------------------- ### Install Cobra Cocoapod Source: https://github.com/picovoice/cobra/blob/main/demo/ios/README.md Run this command to install the Cobra Cocoapod dependency before building the demo app. ```bash pod install ``` -------------------------------- ### Build Cobra Demos with .NET CLI Source: https://github.com/picovoice/cobra/blob/main/demo/dotnet/README.md Builds the microphone and file demos using the .NET CLI. Ensure you have .NET 8.0 installed. ```bash dotnet build -c MicDemo.Release dotnet build -c FileDemo.Release ``` -------------------------------- ### Install Cobra Python Binding Source: https://github.com/picovoice/cobra/blob/main/binding/python/README.md Install the Cobra Python package using pip. ```bash pip3 install pvcobra ``` -------------------------------- ### Install Cobra Nuget Package Source: https://github.com/picovoice/cobra/blob/main/binding/dotnet/README.md Install the latest version of the Cobra Nuget package using the .NET CLI. ```console dotnet add package Cobra ``` -------------------------------- ### Run Cobra Microphone Demo Source: https://github.com/picovoice/cobra/blob/main/demo/nodejs/README.md Starts the Cobra microphone demo for real-time voice activity detection. Requires a working microphone and your Picovoice AccessKey. ```console cobra-mic-demo --access_key ${ACCESS_KEY} ``` -------------------------------- ### Install Cobra Web SDK with NPM Source: https://github.com/picovoice/cobra/blob/main/README.md Use this command to add the Cobra web SDK to your project when using npm. ```bash npm install --save @picovoice/cobra-web ``` -------------------------------- ### Install Cobra Package Source: https://github.com/picovoice/cobra/blob/main/demo/python/README.md Install the Cobra package using pip. Ensure you are using Python 3.9+. ```console sudo pip3 install pvcobrademo ``` -------------------------------- ### Cobra Demo Build and Run Commands Source: https://context7.com/picovoice/cobra/llms.txt Commands for building and running Cobra C demo applications for microphone and file processing. Ensure you have CMake and a compatible C compiler installed. Replace 'YOUR_ACCESS_KEY' with your actual Picovoice access key. ```console # Build microphone and file demo targets cmake -S demo/c/ -B demo/c/build -DPV_RECORDER_PLATFORM=linux cmake --build demo/c/build --target cobra_demo_mic cmake --build demo/c/build --target cobra_demo_file # List audio input devices ./demo/c/build/cobra_demo_mic -s # Run microphone demo ./demo/c/build/cobra_demo_mic \ -l lib/linux/x86_64/libpv_cobra.so \ -a YOUR_ACCESS_KEY \ -d 0 # Process a WAV file ./demo/c/build/cobra_demo_file \ -l lib/linux/x86_64/libpv_cobra.so \ -a YOUR_ACCESS_KEY \ -w /path/to/audio.wav ``` -------------------------------- ### Install Cobra Web SDK Source: https://context7.com/picovoice/cobra/llms.txt Install the Cobra Web SDK using npm or yarn. This package is for browser-based voice activity detection. ```bash npm install @picovoice/cobra-web yarn add @picovoice/cobra-web ``` -------------------------------- ### Install Cobra Web SDK with Yarn Source: https://github.com/picovoice/cobra/blob/main/README.md Use this command to add the Cobra web SDK to your project when using Yarn. ```bash yarn add @picovoice/cobra-web ``` -------------------------------- ### Python SDK: pvcobra.create Source: https://context7.com/picovoice/cobra/llms.txt Initializes the Cobra engine with an access key and provides access to sample rate and frame length properties. The example demonstrates processing an audio file frame by frame. ```APIDOC ## pvcobra.create(access_key) ### Description Initializes the Cobra engine and returns an instance. The `access_key` is required and obtained from the Picovoice Console. The returned handle provides `sample_rate` and `frame_length` properties. ### Method Signature `pvcobra.create(access_key: str)` ### Parameters * **access_key** (str) - Required - Your Picovoice AccessKey. ### Returns An object with `sample_rate` (int), `frame_length` (int), `process` (function), and `delete` (function) methods. ### Example ```python import pvcobra # Initialize engine handle = pvcobra.create(access_key="YOUR_ACCESS_KEY") print(f"Sample rate: {handle.sample_rate}") print(f"Frame length: {handle.frame_length}") # ... process audio using handle.process(pcm_data) ... # Always release resources explicitly handle.delete() ``` ``` -------------------------------- ### Install Cobra NodeJS SDK with Yarn Source: https://github.com/picovoice/cobra/blob/main/README.md Use this command to add the Cobra NodeJS SDK to your project when using Yarn. ```bash yarn add @picovoice/cobra-node ``` -------------------------------- ### Node.js Cobra Demo CLI Commands Source: https://context7.com/picovoice/cobra/llms.txt Commands to install and run the Node.js Cobra demo applications for analyzing audio files. Use `--threshold` to customize voice detection sensitivity. ```console # Install global demo package npm install -g @picovoice/cobra-node-demo # File demo — analyze a WAV file cobra-file-demo --access_key YOUR_ACCESS_KEY --input_audio_file_path audio.wav # File demo with custom threshold cobra-file-demo --access_key YOUR_ACCESS_KEY --input_audio_file_path audio.wav --threshold 0.8 ``` -------------------------------- ### Initialize Cobra Engine and Process Audio Source: https://context7.com/picovoice/cobra/llms.txt Initializes the Cobra engine, lists available hardware devices, and processes audio frames to detect voice activity. Use `pv_sample_rate()` and `pv_cobra_frame_length()` to get the required audio parameters. The `device` parameter can be set to 'best' for auto-selection, 'cpu', 'cpu:N' for N threads, 'gpu', or 'gpu:N' for a specific GPU. ```c #include #include #include #include "pv_cobra.h" int main(void) { const char *access_key = "YOUR_ACCESS_KEY"; // List available hardware devices char **devices = NULL; int32_t num_devices = 0; pv_status_t status = pv_cobra_list_hardware_devices(&devices, &num_devices); if (status == PV_STATUS_SUCCESS) { printf("Available devices:\n"); for (int32_t i = 0; i < num_devices; i++) { printf(" [%d] %s\n", i, devices[i]); } pv_cobra_free_hardware_devices(devices, num_devices); } // Initialize Cobra — use GPU if available, else fallback pv_cobra_t *cobra = NULL; status = pv_cobra_init(access_key, "best", &cobra); if (status != PV_STATUS_SUCCESS) { fprintf(stderr, "Failed to initialize Cobra: %d\n", status); return 1; } printf("Cobra version: %s\n", pv_cobra_version()); printf("Sample rate: %d Hz\n", pv_sample_rate()); printf("Frame length: %d samples\n", pv_cobra_frame_length()); // Allocate audio frame buffer int32_t frame_length = pv_cobra_frame_length(); int16_t *pcm = calloc(frame_length, sizeof(int16_t)); const float THRESHOLD = 0.5f; // Processing loop — fill `pcm` from your audio source for (int frame = 0; frame < 100; frame++) { // TODO: read `frame_length` int16 samples from mic/file into `pcm` float is_voiced = 0.0f; status = pv_cobra_process(cobra, pcm, &is_voiced); if (status != PV_STATUS_SUCCESS) { fprintf(stderr, "Process error: %d\n", status); break; } if (is_voiced >= THRESHOLD) { printf("Frame %d: VOICE detected (p=%.3f)\n", frame, is_voiced); } } free(pcm); pv_cobra_delete(cobra); return 0; } ``` -------------------------------- ### Run Microphone Demo Source: https://context7.com/picovoice/cobra/llms.txt Execute the command-line microphone demo. Replace YOUR_ACCESS_KEY with your actual Picovoice access key. ```bash cobra-mic-demo --access_key YOUR_ACCESS_KEY ``` -------------------------------- ### Run Microphone Demo Source: https://github.com/picovoice/cobra/blob/main/demo/python/README.md Execute the microphone demo to process real-time audio. Replace {AccessKey} with your Picovoice Console AccessKey. ```console cobra_demo_mic --access_key {AccessKey} ``` -------------------------------- ### Run Microphone Demo with Default Device Source: https://github.com/picovoice/cobra/blob/main/demo/dotnet/README.md Runs the microphone demo using the default audio input device. Requires a valid Picovoice AccessKey. ```bash dotnet run -c MicDemo.Release -- --access_key ${ACCESS_KEY} ``` -------------------------------- ### Initialize Cobra Engine Source: https://github.com/picovoice/cobra/blob/main/binding/dotnet/README.md Create an instance of the Cobra engine with your Picovoice AccessKey. Ensure your AccessKey is kept secret. ```csharp using Pv; const string accessKey = "${ACCESS_KEY}"; // Obtained from the Picovoice Console (https://console.picovoice.ai/) Cobra cobra = new Cobra(accessKey); ``` -------------------------------- ### Initialize Cobra Engine Source: https://github.com/picovoice/cobra/blob/main/binding/python/README.md Create an instance of the Cobra engine using your Picovoice AccessKey. Ensure you replace `${AccessKey}` with your actual key. ```python import pvcobra handle = pvcobra.create(access_key=${AccessKey}) ``` -------------------------------- ### Run C Cobra Microphone Demo Source: https://github.com/picovoice/cobra/blob/main/README.md Run the C Cobra microphone demo. Provide the library path, your AccessKey, and the audio device index. Replace placeholders with your specific values. ```console ./demo/c/build/cobra_demo_mic -l ${LIBRARY_PATH} -a ${ACCESS_KEY} -d ${AUDIO_DEVICE_INDEX} ``` -------------------------------- ### pv_cobra_version() - Get Cobra Version Source: https://context7.com/picovoice/cobra/llms.txt Returns the version string of the Cobra library. ```APIDOC ## pv_cobra_version() ### Description Returns the version string of the Cobra library. ### Parameters None ### Response #### Success Response - **version** (`const char *`) - The version string of the Cobra library. #### Response Example ``` "1.0.0" ``` ``` -------------------------------- ### Run Microphone Demo with Specific Device Source: https://github.com/picovoice/cobra/blob/main/demo/dotnet/README.md Runs the microphone demo using a specified audio device index. Obtain the index by first running `--show_audio_devices`. ```bash dotnet run -c MicDemo.Release -- \ --access_key ${ACCESS_KEY} \ --audio_device_index 0 ``` -------------------------------- ### pv_sample_rate() - Get Required Sample Rate Source: https://context7.com/picovoice/cobra/llms.txt Returns the required audio sample rate for the Cobra engine. ```APIDOC ## pv_sample_rate() ### Description Returns the required audio sample rate for the Cobra engine. ### Parameters None ### Response #### Success Response - **sample_rate** (`int32_t`) - The required sample rate in Hz. #### Response Example ``` 16000 ``` ``` -------------------------------- ### Initialize Cobra Engine Source: https://github.com/picovoice/cobra/blob/main/binding/android/README.md Create an instance of the Cobra engine using your Picovoice AccessKey. Handle potential CobraException during initialization. ```java import ai.picovoice.cobra.Cobra; import ai.picovoice.cobra.CobraException; String accessKey = // .. AccessKey obtained from Picovoice Console (https://console.picovoice.ai/) try { handle = new Cobra(accessKey); } catch (CobraException e) { // handle error } ``` -------------------------------- ### Build and Run .NET Cobra Microphone Demo Source: https://github.com/picovoice/cobra/blob/main/README.md Build and run the .NET Cobra microphone demo. Ensure you replace ${ACCESS_KEY} with your Picovoice Console AccessKey. This demo processes audio from the microphone and detects voice activity. ```console dotnet build -c MicDemo.Release dotnet run -c MicDemo.Release -- --access_key ${ACCESS_KEY} ``` -------------------------------- ### Initialize and Process Audio with Node.js Cobra SDK Source: https://context7.com/picovoice/cobra/llms.txt Construct a Cobra instance with an access key and process audio frames from a microphone in real-time. Release resources using `cobra.release()` when done. ```javascript const { Cobra } = require("@picovoice/cobra-node"); const { PvRecorder } = require("@picovoice/pvrecorder-node"); const fs = require("fs"); const accessKey = "YOUR_ACCESS_KEY"; const cobra = new Cobra(accessKey); console.log(`Sample rate: ${cobra.sampleRate}`); console.log(`Frame length: ${cobra.frameLength}`); // Real-time microphone processing const recorder = new PvRecorder(cobra.frameLength, -1 /* default device */); recorder.start(); const THRESHOLD = 0.5; let isVoiceActive = false; console.log("Listening for voice activity... Press Ctrl+C to stop."); process.on("SIGINT", () => { recorder.stop(); recorder.release(); cobra.release(); process.exit(); }); (async () => { while (true) { const audioFrame = await recorder.read(); const voiceProbability = cobra.process(audioFrame); if (voiceProbability >= THRESHOLD && !isVoiceActive) { console.log(`Voice started (probability: ${voiceProbability.toFixed(3)})`); isVoiceActive = true; } else if (voiceProbability < THRESHOLD && isVoiceActive) { console.log("Voice ended"); isVoiceActive = false; } } })(); ``` -------------------------------- ### pv_cobra_frame_length() - Get Required Frame Length Source: https://context7.com/picovoice/cobra/llms.txt Returns the required frame length (in samples) for audio input to the Cobra engine. ```APIDOC ## pv_cobra_frame_length() ### Description Returns the required frame length (in samples) for audio input to the Cobra engine. ### Parameters None ### Response #### Success Response - **frame_length** (`int32_t`) - The required frame length in samples. #### Response Example ``` 512 ``` ``` -------------------------------- ### Initialize Cobra Engine Source: https://github.com/picovoice/cobra/blob/main/binding/ios/README.md Create an instance of the Cobra engine using your Picovoice AccessKey. Ensure the AccessKey is kept secret. ```swift import Cobra let accessKey : String = // .. accessKey provided by Picovoice Console (https://console.picovoice.ai/) do { handle = try Cobra(accessKey: accessKey) } catch { } ``` -------------------------------- ### Initialize Cobra Engine Source: https://github.com/picovoice/cobra/blob/main/binding/nodejs/README.md Create an instance of the Cobra engine using your Picovoice AccessKey. Ensure your AccessKey is kept secret. ```javascript const { Cobra } = require("@picovoice/cobra-node"); const accessKey = "${ACCESS_KEY}"; // Obtained from the Picovoice Console (https://console.picovoice.ai/) const cobra = new Cobra(accessKey); ``` -------------------------------- ### Process Audio Frames Source: https://github.com/picovoice/cobra/blob/main/binding/dotnet/README.md Pass frames of audio (16-bit linearly-encoded PCM, single-channel) to the Cobra engine to get the probability of voice activity. The engine expects frames of `cobra.FrameLength` samples at `cobra.SampleRate`. ```csharp short[] GetNextAudioFrame() { // .. get audioFrame return audioFrame; } while(true) { float voiceProbability = cobra.Process(frame.ToArray()); // .. use probability to trigger other functionality } ``` -------------------------------- ### Initialize C Cobra Engine Source: https://github.com/picovoice/cobra/blob/main/README.md Build an instance of the Cobra object in C. Replace ${ACCESS_KEY} with your AccessKey and ${DEVICE} with the appropriate device identifier. Error handling for `pv_cobra_init` is crucial. ```c pv_status_t status = pv_cobra_init(${ACCESS_KEY}, ${DEVICE}, &handle); if (status != PV_STATUS_SUCCESS) { // error handling logic } ``` -------------------------------- ### Run Cobra File Demo Source: https://github.com/picovoice/cobra/blob/main/demo/nodejs/README.md Executes the Cobra file demo for voice activity detection. Requires your Picovoice AccessKey and a path to an audio file. ```console cobra-file-demo --access_key ${ACCESS_KEY} --input_audio_file_path ${AUDIO_PATH} ``` -------------------------------- ### Initialize and Process Audio with Python PVCobra SDK Source: https://context7.com/picovoice/cobra/llms.txt Initialize the Cobra engine with an access key and process an audio file frame by frame. Ensure the audio is 16kHz mono PCM. Release resources explicitly when done. ```python import pvcobra import wave import struct # Initialize engine handle = pvcobra.create(access_key="YOUR_ACCESS_KEY") print(f"Sample rate: {handle.sample_rate}") # 16000 print(f"Frame length: {handle.frame_length}") # e.g. 512 # Process a WAV file frame by frame THRESHOLD = 0.5 # voice detection threshold [0, 1] with wave.open("audio.wav", "rb") as wf: assert wf.getframerate() == handle.sample_rate, "Audio must be 16kHz" assert wf.getnchannels() == 1, "Audio must be mono" while True: raw = wf.readframes(handle.frame_length) if len(raw) < handle.frame_length * 2: break pcm = struct.unpack(f"{handle.frame_length}h", raw) voice_probability = handle.process(pcm) if voice_probability >= THRESHOLD: print(f"Voice detected! Probability: {voice_probability:.3f}") else: print(f"Silence. Probability: {voice_probability:.3f}") # Always release resources explicitly handle.delete() ``` -------------------------------- ### Specify Audio Device Index Source: https://github.com/picovoice/cobra/blob/main/demo/python/README.md Run the microphone demo using a specific audio device index. Obtain the correct index using the --show_audio_devices command. ```console cobra_demo_mic --access_key {AccessKey} --audio_device_index 10 ``` -------------------------------- ### Build Cobra File Demo with CMake Source: https://github.com/picovoice/cobra/blob/main/demo/c/README.md Use CMake to build the file demo. The PV_RECORDER_PLATFORM variable sets compilation flags for the target platform. ```console cmake -S demo/c/ -B demo/c/build -DPV_RECORDER_PLATFORM={PV_RECORDER_PLATFORM} cmake --build demo/c/build --target cobra_demo_file ``` -------------------------------- ### pv_cobra_init() - Initialize Cobra Engine Source: https://context7.com/picovoice/cobra/llms.txt Initializes the Cobra engine with a specified hardware device. The `device` parameter allows for auto-selection ('best'), CPU usage ('cpu', 'cpu:N'), or GPU usage ('gpu', 'gpu:N'). Use `pv_sample_rate()` and `pv_cobra_frame_length()` to determine the required audio sample rate and frame size. ```APIDOC ## pv_cobra_init() ### Description Constructs a `pv_cobra_t` instance. The `device` parameter supports `"best"` (auto-select), `"cpu"`, `"cpu:4"` (4 threads), `"gpu"`, or `"gpu:0"` (specific GPU index). Use `pv_sample_rate()` for the required sample rate and `pv_cobra_frame_length()` for the frame size. ### Parameters #### Path Parameters - **access_key** (string) - Required - Your Picovoice license AccessKey. - **device** (string) - Required - Hardware device selection string (e.g., `"best"`, `"cpu"`, `"gpu:0"`). #### Request Body None ### Response #### Success Response (PV_STATUS_SUCCESS) - **cobra** (`pv_cobra_t **`) - Pointer to the initialized Cobra engine instance. #### Error Response - **status** (`pv_status_t`) - An error code indicating the failure reason. ``` -------------------------------- ### Cobra Initialization Source: https://github.com/picovoice/cobra/blob/main/binding/nodejs/README.md Initialize the Cobra engine with your Picovoice AccessKey. The AccessKey is required for authentication and can be obtained from the Picovoice Console. ```APIDOC ## Cobra Initialization ### Description Initialize the Cobra engine with your Picovoice AccessKey. The AccessKey is required for authentication and can be obtained from the Picovoice Console. ### Method `new Cobra(accessKey)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript const { Cobra } = require("@picovoice/cobra-node"); const accessKey = "${ACCESS_KEY}"; // Obtained from the Picovoice Console (https://console.picovoice.ai/) const cobra = new Cobra(accessKey); ``` ### Response #### Success Response (200) An instance of the Cobra engine. #### Response Example ```javascript // cobra instance ``` ``` -------------------------------- ### Build Cobra Microphone Demo with CMake Source: https://github.com/picovoice/cobra/blob/main/demo/c/README.md Use CMake to build the microphone demo. The PV_RECORDER_PLATFORM variable sets compilation flags for the target platform. ```console cmake -S demo/c/ -B demo/c/build -DPV_RECORDER_PLATFORM={PV_RECORDER_PLATFORM} cmake --build demo/c/build --target cobra_demo_mic ``` -------------------------------- ### Cobra File Demo Usage Source: https://github.com/picovoice/cobra/blob/main/demo/c/README.md Run the file demo executable to analyze an audio file. Specify the library path, AccessKey, and the input WAV file path. The WAV file must be single-channel, 16kHz, and 16-bit PCM. ```console ./demo/c/build/cobra_demo_file -l ${LIBRARY_PATH} -a ${ACCESS_KEY} -w ${INPUT_WAV_FILE} ``` -------------------------------- ### List Available Audio Devices Source: https://github.com/picovoice/cobra/blob/main/demo/dotnet/README.md Lists all available audio input devices on the system. Useful for selecting a specific microphone for the demo. ```bash dotnet run -c MicDemo.Release -- --show_audio_devices ``` -------------------------------- ### Show Available Audio Devices Source: https://github.com/picovoice/cobra/blob/main/demo/python/README.md List available audio input devices to help select the correct one for the microphone demo. This is useful if the default device is not functioning as expected. ```console cobra_demo_mic --show_audio_devices ``` -------------------------------- ### Build C Cobra Microphone Demo Source: https://github.com/picovoice/cobra/blob/main/README.md Build the C demo for Cobra using CMake. This command compiles the microphone demo executable. ```console cmake -S demo/c/ -B demo/c/build && cmake --build demo/c/build --target cobra_demo_mic ``` -------------------------------- ### Initialize iOS Cobra Engine Source: https://github.com/picovoice/cobra/blob/main/README.md Create an instance of the Cobra engine in iOS. Replace the placeholder with your AccessKey from the Picovoice Console. Handle potential errors during initialization. ```swift import Cobra let accessKey : String = // .. AccessKey provided by Picovoice Console (https://console.picovoice.ai/) do { handle = try Cobra(accessKey: accessKey) } catch { } ``` -------------------------------- ### Python PVCobra Demo CLI Commands Source: https://context7.com/picovoice/cobra/llms.txt Commands to run the Python Cobra demo applications for microphone and file processing. Use `--show_audio_devices` to list available microphones. ```console # Install demo package pip3 install pvcobrademo # List available audio input devices cobra_demo_mic --show_audio_devices # Run microphone demo with default device cobra_demo_mic --access_key YOUR_ACCESS_KEY # Run with a specific device index and save output cobra_demo_mic --access_key YOUR_ACCESS_KEY --audio_device_index 10 --output_path ~/recording.wav # Process an audio file with a custom threshold cobra_demo_file --access_key YOUR_ACCESS_KEY --input_audio_path audio.wav --threshold 0.9 ``` -------------------------------- ### NodeJS SDK Usage Source: https://github.com/picovoice/cobra/blob/main/README.md Instantiate Cobra and process audio frames in a NodeJS environment. ```APIDOC ## NodeJS Install NodeJS SDK: ```console yarn add @picovoice/cobra-node ``` Create instances of the Cobra class: ```javascript const { Cobra } = require("@picovoice/cobra-node"); const accessKey = "${ACCESS_KEY}"; // Obtained from the Picovoice Console (https://console.picovoice.ai/) const cobra = new Cobra(accessKey); function getNextAudioFrame() { // ... return audioFrame; } while (true) { const audioFrame = getNextAudioFrame(); const voiceProbability = cobra.process(audioFrame); console.log(voiceProbability); } // When done be sure to release resources using `release()`: cobra.release(); ``` ``` -------------------------------- ### Cobra Microphone Demo Usage Source: https://github.com/picovoice/cobra/blob/main/demo/c/README.md Run the microphone demo executable. Provide library path, AccessKey, and audio device index. Use -1 for the default recording device. ```console ./cobra_demo_mic -s ``` ```console ./demo/c/build/cobra_demo_mic -l ${LIBRARY_PATH} -a ${ACCESS_KEY} -d ${AUDIO_DEVICE_INDEX} ``` -------------------------------- ### Run Python Cobra Microphone Demo Source: https://github.com/picovoice/cobra/blob/main/README.md Execute the Cobra microphone demo in the terminal. Replace ${AccessKey} with your Picovoice Console AccessKey. This will process audio input from your microphone in real-time and indicate voice activity. ```console cobra_demo_mic --access_key ${AccessKey} ``` -------------------------------- ### Initialize Android Cobra Engine Source: https://github.com/picovoice/cobra/blob/main/README.md Create an instance of the Cobra engine in Android. Replace the placeholder with your AccessKey obtained from the Picovoice Console. Handle `CobraException` during initialization. ```java import ai.picovoice.cobra.Cobra; import ai.picovoice.cobra.CobraException; String accessKey = // .. AccessKey provided by Picovoice Console (https://console.picovoice.ai/) try { handle = new Cobra(accessKey); } catch (CobraException e) { // handle error } ``` -------------------------------- ### Cobra Initialization (Main Thread) Source: https://github.com/picovoice/cobra/blob/main/binding/web/README.md Initializes the Cobra engine on the main thread. Requires a voice probability callback and optional error callback. ```APIDOC ## Cobra.create ### Description Initializes the Cobra engine on the main thread. This function requires a valid Picovoice AccessKey and a callback function to receive voice probability results. An optional options object can be provided to specify an error callback. ### Parameters - **accessKey** (string) - Required - Your Picovoice AccessKey. - **voiceProbabilityCallback** (function) - Required - A callback function that receives the voice probability (a number between 0 and 1). - **options** (object) - Optional - An object that may contain an `processErrorCallback` function. - **processErrorCallback** (function) - Optional - A callback function to handle errors during audio processing. ### Returns - Promise - A Promise that resolves to an initialized Cobra instance. ### Example ```typescript const ACCESS_KEY = "YOUR_ACCESS_KEY"; function voiceProbabilityCallback(voiceProbability: number) { console.log("Voice Probability:", voiceProbability); } const options = { processErrorCallback: (error: string) => { console.error("Cobra Error:", error); } }; const cobra = await Cobra.create(ACCESS_KEY, voiceProbabilityCallback, options); ``` ``` -------------------------------- ### Local Web Server Information Source: https://github.com/picovoice/cobra/blob/main/demo/web/README.md Indicates the URL where the Cobra web demo is available. Access it in your browser to use the demo. ```console http://localhost:5000 ``` -------------------------------- ### Add Access Key to local.properties Source: https://github.com/picovoice/cobra/blob/main/demo/android/Activity/README.md Add your Picovoice Console-generated AccessKey to the local.properties file using the pvTestingAccessKey field. ```properties pvTestingAccessKey=YOUR_ACCESS_KEY_HERE ``` -------------------------------- ### Run File Demo for Audio Processing Source: https://github.com/picovoice/cobra/blob/main/demo/dotnet/README.md Processes a specified audio file using the Cobra engine. Accepts 16kHz single-channel audio files. Requires a valid Picovoice AccessKey. ```bash dotnet run -c FileDemo.Release -- \ --input_audio_path ${AUDIO_PATH} \ --access_key ${ACCESS_KEY} ``` -------------------------------- ### Initialize Cobra on Main Thread Source: https://github.com/picovoice/cobra/blob/main/binding/web/README.md Initialize the Cobra engine on the main browser thread. Requires a valid Picovoice AccessKey, a voice probability callback, and an options object. ```typescript const cobra = await Cobra.create( ${ACCESS_KEY}, voiceProbabilityCallback, options ); ``` -------------------------------- ### Run File Demo with Custom Threshold Source: https://github.com/picovoice/cobra/blob/main/demo/dotnet/README.md Processes an audio file with a custom voice activity detection threshold. The threshold is a float between 0 and 1. ```bash dotnet run -c FileDemo.Release -- \ --input_audio_path ${AUDIO_PATH} \ --access_key ${ACCESS_KEY} \ --threshold 0.7 ``` -------------------------------- ### Define Cobra Microphone Demo Executable Source: https://github.com/picovoice/cobra/blob/main/demo/c/CMakeLists.txt Defines the 'cobra_demo_mic' executable, including its source file and the pv_recorder object. It sets private include directories for the recorder. ```cmake add_executable( cobra_demo_mic cobra_demo_mic.c $) target_include_directories(cobra_demo_mic PRIVATE pvrecorder/project/include) ``` -------------------------------- ### Set C Standard and Build Type Source: https://github.com/picovoice/cobra/blob/main/demo/c/CMakeLists.txt Configures the C standard to C99 and sets the build type to Release for optimal performance. ```cmake set(CMAKE_C_STANDARD 99) set(CMAKE_BUILD_TYPE Release) ``` -------------------------------- ### Record Audio to File Source: https://github.com/picovoice/cobra/blob/main/demo/python/README.md Record audio from a specified device and save it to a WAV file for inspection. This is helpful for debugging audio input issues. ```console cobra_demo_mic --access_key {AccessKey} --audio_device_index 10 --output_path ~/test.wav ``` -------------------------------- ### Record Microphone Audio to WAV File Source: https://github.com/picovoice/cobra/blob/main/demo/dotnet/README.md Records audio from the specified microphone to a WAV file for quality testing. Requires a valid Picovoice AccessKey. ```bash dotnet run -c MicDemo.Release -- \ --access_key ${ACCESS_KEY} \ --audio_device_index 0 \ --output_path ./test.wav ``` -------------------------------- ### pv_cobra_list_hardware_devices() - List Available Hardware Devices Source: https://context7.com/picovoice/cobra/llms.txt Retrieves a list of available hardware devices that can be used for acceleration. ```APIDOC ## pv_cobra_list_hardware_devices() ### Description Retrieves a list of available hardware devices that can be used for acceleration. ### Parameters None ### Response #### Success Response (PV_STATUS_SUCCESS) - **devices** (`char ***`) - A dynamically allocated array of strings, where each string is the name of an available hardware device. - **num_devices** (`int32_t *`) - A pointer to an integer that will be populated with the number of devices in the `devices` array. #### Response Example ``` Available devices: [0] cpu [1] gpu:0 ``` ### Note Remember to free the allocated `devices` array using `pv_cobra_free_hardware_devices()` after use. ``` -------------------------------- ### Define Cobra File Demo Executable Source: https://github.com/picovoice/cobra/blob/main/demo/c/CMakeLists.txt Defines the 'cobra_demo_file' executable and specifies its source file. It also sets private include directories. ```cmake add_executable( cobra_demo_file cobra_demo_file.c) target_include_directories(cobra_demo_file PRIVATE dr_libs) ``` -------------------------------- ### Swift Voice Activity Detection Source: https://context7.com/picovoice/cobra/llms.txt Creates a Cobra instance that processes 16-bit mono PCM audio. Use the static `Cobra.sampleRate` and `Cobra.frameLength` properties to set up your `AVAudioEngine` tap. The `process(_:)` method returns a `Float` probability and throws on error. Always call `delete()` to free native resources. ```APIDOC ## Cobra(accessKey:) ### Description Creates a Cobra instance that processes 16-bit mono PCM audio. Use the static `Cobra.sampleRate` and `Cobra.frameLength` properties to set up your `AVAudioEngine` tap. The `process(_:)` method returns a `Float` probability and throws on error. Always call `delete()` to free native resources. ### Parameters #### Path Parameters - **accessKey** (string) - Required - The access key for Cobra. ### Request Example ```swift import Cobra import AVFoundation class VoiceActivityDetector { private var cobra: Cobra? private let audioEngine = AVAudioEngine() private let THRESHOLD: Float = 0.5 func start(accessKey: String) { do { cobra = try Cobra(accessKey: accessKey) let sampleRate = Double(Cobra.sampleRate) let frameLength = AVAudioFrameCount(Cobra.frameLength) let inputNode = audioEngine.inputNode let format = AVAudioFormat( commonFormat: .pcmFormatInt16, sampleRate: sampleRate, channels: 1, interleaved: true )! inputNode.installTap(onBus: 0, bufferSize: frameLength, format: format) { [weak self] buffer, _ in guard let self = self, let channelData = buffer.int16ChannelData else { return } let frameCount = Int(buffer.frameLength) let audioFrame = Array(UnsafeBufferPointer(start: channelData[0], count: frameCount)) do { let voiceProbability = try self.cobra!.process(audioFrame) if voiceProbability >= self.THRESHOLD { print("Voice detected: \(voiceProbability)") } } catch { print("Cobra error: \(error)") } } try audioEngine.start() print("Listening for voice activity...") } catch { print("Failed to start: \(error)") } } func stop() { audioEngine.stop() audioEngine.inputNode.removeTap(onBus: 0) cobra?.delete() } } ``` ### Response #### Success Response (200) - **voiceProbability** (Float) - The probability of voice activity in the current audio frame. ### Error Handling - Throws an error if the Cobra instance cannot be created or if processing fails. ``` -------------------------------- ### Python SDK: handle.process Source: https://context7.com/picovoice/cobra/llms.txt Processes a frame of audio data and returns the voice probability. ```APIDOC ## handle.process(pcm) ### Description Processes a frame of audio data and returns the probability of voice activity. ### Method `handle.process(pcm: list[int]) -> float` ### Parameters * **pcm** (list[int]) - Required - A list of 16-bit PCM audio samples representing a single frame. ### Returns A float between 0 and 1 indicating the probability of voice activity in the frame. ### Example ```python # Assuming 'handle' is an initialized Cobra engine instance # and 'pcm' is a list of audio samples for one frame voice_probability = handle.process(pcm) if voice_probability > 0.5: print(f"Voice detected: {voice_probability:.3f}") else: print(f"Silence: {voice_probability:.3f}") ``` ``` -------------------------------- ### Run Cobra File Demo with Threshold Source: https://github.com/picovoice/cobra/blob/main/demo/nodejs/README.md Runs the Cobra file demo with a specified detection threshold. Adjust the threshold between 0 and 1 to tune miss rate and false alarm rate. ```console cobra-file-demo --access_key ${ACCESS_KEY} --input_audio_file_path ${AUDIO_PATH} --threshold ${DETECTION_THRESHOLD} ``` -------------------------------- ### Web SDK Usage Source: https://github.com/picovoice/cobra/blob/main/README.md Instantiate CobraWorker and process audio streams in the browser. ```APIDOC ## Web SDK Install the web SDK using yarn: ```console yarn add @picovoice/cobra-web ``` or using npm: ```console npm install --save @picovoice/cobra-web ``` Create an instance of the engine using `CobraWorker` and run the VAD on an audio input stream: ```typescript import { CobraWorker } from "@picovoice/cobra-web"; function voiceProbabilityCallback(voiceProbability: number) { // ... use voice probability figure } function getAudioData(): Int16Array { // ... function to get audio data return new Int16Array(); } const cobra = await CobraWorker.create( "${ACCESS_KEY}", voiceProbabilityCallback ); for (; ; ) { cobra.process(getAudioData()); // break on some condition } // When done, release the resources allocated to Cobra using `cobra.release()`. ``` -------------------------------- ### List C Cobra Demo Audio Devices Source: https://github.com/picovoice/cobra/blob/main/README.md List available audio input devices for the C Cobra demo. This helps in identifying the correct microphone index. ```console ./demo/c/build/cobra_demo_mic -s ``` -------------------------------- ### Create Cobra Worker Instance (Web) Source: https://github.com/picovoice/cobra/blob/main/README.md Instantiate CobraWorker for web applications. Ensure you provide your Picovoice access key and a callback function to handle voice probability results. The audio data is obtained from `getAudioData()`. ```typescript import { CobraWorker } from "@picovoice/cobra-web"; function voiceProbabilityCallback(voiceProbability: number) { ... // use voice probability figure } function getAudioData(): Int16Array { ... // function to get audio data return new Int16Array(); } const cobra = await CobraWorker.create( "${ACCESS_KEY}", voiceProbabilityCallback ); for (; ;) { cobra.process(getAudioData()); // break on some condition } ``` -------------------------------- ### Add Cobra Recorder Subdirectory Source: https://github.com/picovoice/cobra/blob/main/demo/c/CMakeLists.txt Includes the pvrecorder subdirectory, which is necessary for microphone input functionality. ```cmake add_subdirectory(pvrecorder/project) ``` -------------------------------- ### Android Manifest Permissions Source: https://github.com/picovoice/cobra/blob/main/binding/android/README.md Add INTERNET and RECORD_AUDIO permissions to your AndroidManifest.xml to enable microphone access and communication with the license server. ```xml ``` -------------------------------- ### Cobra Initialization (Worker Thread) Source: https://github.com/picovoice/cobra/blob/main/binding/web/README.md Initializes the Cobra engine on a web worker thread. This is recommended for performance and requires a voice probability callback and optional error callback. ```APIDOC ## CobraWorker.create ### Description Initializes the Cobra engine on a web worker thread for improved performance. This function requires a valid Picovoice AccessKey and a callback function to receive voice probability results. An optional options object can be provided to specify an error callback. ### Parameters - **accessKey** (string) - Required - Your Picovoice AccessKey. - **voiceProbabilityCallback** (function) - Required - A callback function that receives the voice probability (a number between 0 and 1). - **options** (object) - Optional - An object that may contain an `processErrorCallback` function. - **processErrorCallback** (function) - Optional - A callback function to handle errors during audio processing. ### Returns - Promise - A Promise that resolves to an initialized CobraWorker instance. ### Example ```typescript const ACCESS_KEY = "YOUR_ACCESS_KEY"; function voiceProbabilityCallback(voiceProbability: number) { console.log("Voice Probability:", voiceProbability); } const options = { processErrorCallback: (error: string) => { console.error("Cobra Worker Error:", error); } }; const cobraWorker = await CobraWorker.create(ACCESS_KEY, voiceProbabilityCallback, options); ``` ``` -------------------------------- ### Node.js SDK: new Cobra Source: https://context7.com/picovoice/cobra/llms.txt Constructs a Cobra instance for Node.js. Provides sample rate and frame length properties. The process method accepts an Int16Array. ```APIDOC ## new Cobra(accessKey) ### Description Constructs a new Cobra instance. Use `cobra.sampleRate` and `cobra.frameLength` to configure your audio pipeline. The `process(frame)` method accepts an `Int16Array` and returns a voice probability number. Always call `cobra.release()` when done to free native resources. ### Constructor `new Cobra(accessKey: string)` ### Parameters * **accessKey** (string) - Required - Your Picovoice AccessKey. ### Properties * **sampleRate** (number) - The audio sample rate (always 16000). * **frameLength** (number) - The number of audio samples per frame. ### Example ```javascript const { Cobra } = require("@picovoice/cobra-node"); const accessKey = "YOUR_ACCESS_KEY"; const cobra = new Cobra(accessKey); console.log(`Sample rate: ${cobra.sampleRate}`); console.log(`Frame length: ${cobra.frameLength}`); // ... process audio frames using cobra.process(audioFrame) ... // Release resources when done cobra.release(); ``` ``` -------------------------------- ### Replace Access Key in MainActivity.java Source: https://github.com/picovoice/cobra/blob/main/demo/android/Activity/README.md Replace the placeholder with your Picovoice Console-generated AccessKey within the MainActivity.java file. ```java private static final String ACCESS_KEY = "YOUR_ACCESS_KEY_HERE"; ``` -------------------------------- ### Configure Microphone Usage in Info.plist Source: https://github.com/picovoice/cobra/blob/main/binding/ios/README.md Add the NSMicrophoneUsageDescription key to your app's Info.plist file to request microphone access. ```xml NSMicrophoneUsageDescription [Permission explanation] ``` -------------------------------- ### Initialize Cobra for Android Java Source: https://context7.com/picovoice/cobra/llms.txt Construct a Cobra instance for Java voice activity detection on Android. Configure AudioRecord using getSampleRate() and getFrameLength(). ```java import ai.picovoice.cobra.Cobra; import ai.picovoice.cobra.CobraException; import android.media.AudioFormat; import android.media.AudioRecord; import android.media.MediaRecorder; public class VoiceActivityDetector { private Cobra cobra; private AudioRecord audioRecord; private boolean isRecording = false; private static final float THRESHOLD = 0.5f; public void start(String accessKey) { try { cobra = new Cobra(accessKey); int frameLength = cobra.getFrameLength(); int sampleRate = cobra.getSampleRate(); int bufferSize = AudioRecord.getMinBufferSize( sampleRate, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT ); audioRecord = new AudioRecord( MediaRecorder.AudioSource.MIC, sampleRate, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, Math.max(bufferSize, frameLength * 2) ); short[] audioFrame = new short[frameLength]; audioRecord.startRecording(); isRecording = true; new Thread(() -> { while (isRecording) { audioRecord.read(audioFrame, 0, frameLength); try { float voiceProbability = cobra.process(audioFrame); if (voiceProbability >= THRESHOLD) { // Voice detected — trigger UI update or event System.out.println("Voice: " + voiceProbability); } } catch (CobraException e) { e.printStackTrace(); } } }).start(); } catch (CobraException e) { e.printStackTrace(); } } public void stop() { isRecording = false; if (audioRecord != null) audioRecord.stop(); if (cobra != null) cobra.delete(); } } ``` -------------------------------- ### Run Cobra File Demo with Custom Threshold Source: https://github.com/picovoice/cobra/blob/main/demo/python/README.md This command processes an audio file with a specified detection threshold. Adjust the `threshold` value (between 0 and 1) to tune miss rate and false alarm rate. A higher threshold reduces miss rate at the cost of increased false alarms. ```console cobra_demo_file --access_key {AccessKey} --input_audio_path ${AUDIO_PATH} \ --threshold 0.9 ``` -------------------------------- ### C# Voice Activity Detection Source: https://context7.com/picovoice/cobra/llms.txt Constructs a Cobra instance. `SampleRate` and `FrameLength` properties configure the audio pipeline. The `Process(frame)` method accepts a `short[]` and returns a `float` probability in `[0, 1]`. Implements `IDisposable` — wrap in a `using` statement for deterministic resource cleanup. ```APIDOC ## new Cobra(accessKey) ### Description Constructs a Cobra instance. `SampleRate` and `FrameLength` properties configure the audio pipeline. The `Process(frame)` method accepts a `short[]` and returns a `float` probability in `[0, 1]`. Implements `IDisposable` — wrap in a `using` statement for deterministic resource cleanup. ### Parameters #### Path Parameters - **accessKey** (string) - Required - The access key for Cobra. ### Request Example ```csharp using Pv; using System; class VoiceActivityDetector { static void Main(string[] args) { const string accessKey = "YOUR_ACCESS_KEY"; const float threshold = 0.5f; using (Cobra cobra = new Cobra(accessKey)) { Console.WriteLine($"Sample rate: {cobra.SampleRate}"); Console.WriteLine($"Frame length: {cobra.FrameLength}"); // Simulated audio frame processing loop // In practice, read frames from microphone or WAV file short[] GetNextAudioFrame() { // Replace with actual audio capture (e.g., NAudio, PvRecorder) return new short[cobra.FrameLength]; } Console.WriteLine("Processing audio... Press Ctrl+C to stop."); bool voiceWasActive = false; while (true) { short[] frame = GetNextAudioFrame(); float voiceProbability = cobra.Process(frame); bool voiceIsActive = voiceProbability >= threshold; if (voiceIsActive && !voiceWasActive) Console.WriteLine($"Voice started (p={voiceProbability:F3})"); else if (!voiceIsActive && voiceWasActive) Console.WriteLine("Voice ended"); voiceWasActive = voiceIsActive; } } // cobra.Dispose() called automatically here } } ``` ### Response #### Success Response (200) - **voiceProbability** (float) - The probability of voice activity in the current audio frame. ### Error Handling - Implements `IDisposable` for resource management. ``` -------------------------------- ### Swift Voice Activity Detection with Cobra Source: https://context7.com/picovoice/cobra/llms.txt Creates a Cobra instance for processing 16-bit mono PCM audio. Ensure to call `delete()` to free native resources. Use `Cobra.sampleRate` and `Cobra.frameLength` to configure your `AVAudioEngine`. ```swift import Cobra import AVFoundation class VoiceActivityDetector { private var cobra: Cobra? private let audioEngine = AVAudioEngine() private let THRESHOLD: Float = 0.5 func start(accessKey: String) { do { cobra = try Cobra(accessKey: accessKey) let sampleRate = Double(Cobra.sampleRate) let frameLength = AVAudioFrameCount(Cobra.frameLength) let inputNode = audioEngine.inputNode let format = AVAudioFormat( commonFormat: .pcmFormatInt16, sampleRate: sampleRate, channels: 1, interleaved: true )! inputNode.installTap(onBus: 0, bufferSize: frameLength, format: format) { [weak self] buffer, _ in guard let self = self, let channelData = buffer.int16ChannelData else { return } let frameCount = Int(buffer.frameLength) let audioFrame = Array(UnsafeBufferPointer(start: channelData[0], count: frameCount)) do { let voiceProbability = try self.cobra!.process(audioFrame) if voiceProbability >= self.THRESHOLD { print("Voice detected: \(voiceProbability)") } } catch { print("Cobra error: \(error)") } } try audioEngine.start() print("Listening for voice activity...") } catch { print("Failed to start: \(error)") } } func stop() { audioEngine.stop() audioEngine.inputNode.removeTap(onBus: 0) cobra?.delete() } } ```