### Install Packages Source: https://github.com/analyticsinmotion/decibri/blob/main/docs/docs/node/integrations/azure-speech.html Install the necessary npm packages: decibri, the Azure Speech SDK, and dotenv for environment variable management. ```bash npm install decibri microsoft-cognitiveservices-speech-sdk dotenv ``` -------------------------------- ### Install Packages Source: https://github.com/analyticsinmotion/decibri/blob/main/docs/docs/node/integrations/assemblyai.html Installs the necessary npm packages for decibri, AssemblyAI, and dotenv. ```bash $ npm install decibri assemblyai dotenv ``` -------------------------------- ### Quick Start: Capture and Log Microphone Audio Source: https://github.com/analyticsinmotion/decibri/blob/main/docs/docs/browser/index.html Instantiate Decibri, listen for 'data' events to receive audio chunks, and start capturing. Note: 'start()' requires a user gesture in Safari. ```javascript import { Decibri } from 'decibri-web'; const mic = new Decibri({ sampleRate: 16000 }); mic.on('data', (chunk) => { console.log(`Received ${chunk.length} samples`); }); await mic.start(); ``` -------------------------------- ### Install dependencies Source: https://github.com/analyticsinmotion/decibri/blob/main/docs/docs/node/integrations/sherpa-onnx-kws.html Install the required packages via npm. ```bash npm install decibri sherpa-onnx ``` -------------------------------- ### Full Example: Real-time Transcription Source: https://github.com/analyticsinmotion/decibri/blob/main/docs/docs/node/integrations/google-speech.html This complete example integrates Decibri with Google Cloud Speech-to-Text for live audio transcription. It includes setup, stream creation, audio piping, and result handling. ```javascript 'use strict'; require('dotenv').config(); const Decibri = require('decibri'); const speech = require('@google-cloud/speech'); async function main() { // Create client (uses GOOGLE_APPLICATION_CREDENTIALS env var) const client = new speech.SpeechClient(); // Configure streaming recognition const request = { config: { encoding: 'LINEAR16', sampleRateHertz: 16000, languageCode: 'en-US', }, interimResults: true, }; // Create the recognize stream const recognizeStream = client .streamingRecognize(request) .on('error', console.error) .on('data', (data) => { const result = data.results[0]; if (result && result.alternatives[0]) { const transcript = result.alternatives[0].transcript; if (result.isFinal) { console.log(`\n [final] ${transcript}`); } else { process.stdout.write(`\r [partial] ${transcript} `); } } }); // Open microphone and pipe to Google const mic = new Decibri({ sampleRate: 16000, channels: 1 }); mic.pipe(recognizeStream); console.log('Google Speech-to-Text streaming test'); console.log('Speak into your microphone. Press Ctrl+C to stop.\n'); } // ── Cleanup on Ctrl+C ────────────────────────────────────── process.on('SIGINT', () => { console.log('\nStopping...'); process.exit(0); }); main().catch(console.error); ``` -------------------------------- ### Install Required Packages Source: https://github.com/analyticsinmotion/decibri/blob/main/docs/docs/node/integrations/google-speech.html Install the necessary dependencies for decibri and Google Cloud Speech-to-Text. ```bash npm install decibri @google-cloud/speech dotenv ``` -------------------------------- ### Install decibri-web via npm Source: https://github.com/analyticsinmotion/decibri/blob/main/docs/docs/browser/index.html Use npm to install the decibri-web package for browser-based microphone capture. ```bash $ npm install decibri-web ``` -------------------------------- ### Install Dependencies and Build Native Addon Source: https://github.com/analyticsinmotion/decibri/blob/main/CONTRIBUTING.md Install project dependencies and build the native Node.js addon. This command compiles PortAudio and the C++ addon using node-gyp. ```bash npm install ``` -------------------------------- ### Install Required Packages Source: https://github.com/analyticsinmotion/decibri/blob/main/docs/docs/node/integrations/openai-realtime.html Command to install the necessary dependencies for the integration. ```bash npm install decibri ws dotenv ``` -------------------------------- ### Complete keyword spotting implementation Source: https://github.com/analyticsinmotion/decibri/blob/main/docs/docs/node/integrations/sherpa-onnx-kws.html A full example demonstrating initialization, audio processing, and resource cleanup. ```javascript const Decibri = require('decibri'); const sherpa = require('sherpa-onnx'); const modelDir = './sherpa-onnx-kws-zipformer-wenetspeech-3.3M-2024-01-01'; const config = { featConfig: { sampleRate: 16000, featureDim: 80 }, modelConfig: { transducer: { encoder: `${modelDir}/encoder-epoch-12-avg-2-chunk-16-left-64.onnx`, decoder: `${modelDir}/decoder-epoch-12-avg-2-chunk-16-left-64.onnx`, joiner: `${modelDir}/joiner-epoch-12-avg-2-chunk-16-left-64.onnx`, }, tokens: `${modelDir}/tokens.txt`, numThreads: 2, provider: 'cpu', }, keywordsFile: `${modelDir}/keywords.txt`, }; const kws = new sherpa.KeywordSpotter(config); const stream = kws.createStream(); const mic = new Decibri({ sampleRate: 16000, channels: 1 }); mic.on('data', (chunk) => { const int16 = new Int16Array(chunk.buffer, chunk.byteOffset, chunk.length / 2); const float32 = new Float32Array(int16.length); for (let i = 0; i < int16.length; i++) { float32[i] = int16[i] / 32768; } stream.acceptWaveform(16000, float32); while (kws.isReady(stream)) { kws.decode(stream); } const keyword = kws.getResult(stream).keyword; if (keyword) { console.log(`Detected: "${keyword}"`); } }); process.on('SIGINT', () => { mic.stop(); stream.free(); kws.free(); process.exit(0); }); console.log('Listening for keywords... (Ctrl+C to stop)'); ``` -------------------------------- ### Enumerate and Select Audio Devices Source: https://github.com/analyticsinmotion/decibri/blob/main/docs/docs/browser/index.html Start the microphone first to trigger permission, then use 'Decibri.devices()' to get a list of available audio input devices. You can then instantiate Decibri with a specific 'deviceId'. ```javascript // Start first to trigger permission, then enumerate with labels await mic.start(); const devices = await Decibri.devices(); console.log(devices); // [{ deviceId: 'abc123', label: 'Built-in Microphone', groupId: 'g1' }, ...] // Use a specific device const usbMic = new Decibri({ device: devices[1].deviceId }); await usbMic.start(); ``` -------------------------------- ### Full Example: Live Audio Streaming with Decibri and Deepgram SDK Source: https://github.com/analyticsinmotion/decibri/blob/main/docs/docs/node/integrations/deepgram.html This complete example demonstrates setting up a Deepgram connection, handling messages, streaming audio from a microphone using Decibri, and managing connection lifecycle events. ```javascript 'use strict'; require('dotenv').config(); const Decibri = require('decibri'); const { DeepgramClient } = require('@deepgram/sdk'); const live = async () => { const deepgram = new DeepgramClient({ apiKey: process.env.DEEPGRAM_API_KEY }); const socket = await deepgram.listen.v1.createConnection({ model: 'nova-3', language: 'en', encoding: 'linear16', sample_rate: 16000, channels: 1, punctuate: true, smart_format: true, }); socket.on('message', (data) => { if (data.type === 'Results' && data.channel?.alternatives?.[0]) { const transcript = data.channel.alternatives[0].transcript; if (transcript) { console.log(transcript); } } }); socket.on('close', () => { console.log('Connection closed.'); process.exit(0); }); socket.on('error', (err) => { console.error('Deepgram error:', err); }); socket.connect(); await socket.waitForOpen(); const mic = new Decibri({ sampleRate: 16000, channels: 1 }); mic.on('data', (chunk) => { socket.sendMedia(chunk); }); mic.on('error', (err) => { console.error('Mic error:', err.message); }); process.on('SIGINT', () => { console.log('\nStopping...'); mic.stop(); socket.requestClose(); }); console.log('Listening... (Ctrl+C to stop)\n'); }; live().catch(console.error); ``` -------------------------------- ### Full AssemblyAI and Decibri Integration Example Source: https://github.com/analyticsinmotion/decibri/blob/main/docs/docs/node/integrations/assemblyai.html A complete implementation demonstrating the full flow from client initialization to event handling and audio streaming. ```javascript 'use strict'; require('dotenv').config(); const Decibri = require('decibri'); const { AssemblyAI } = require('assemblyai'); const run = async () => { const client = new AssemblyAI({ apiKey: process.env.ASSEMBLYAI_API_KEY }); const transcriber = client.streaming.transcriber({ speechModel: 'u3-rt-pro', sampleRate: 16_000, }); transcriber.on('open', ({ id }) => { console.log('AssemblyAI connected. Session:', id); }); transcriber.on('turn', (turn) => { if (turn.end_of_turn && turn.transcript) { console.log(turn.transcript); } }); transcriber.on('error', (err) => { console.error('AssemblyAI error:', err); }); transcriber.on('close', (code, reason) => { console.log('Connection closed:', code, reason); }); await transcriber.connect(); const mic = new Decibri({ sampleRate: 16000, channels: 1 }); mic.on('data', (chunk) => { transcriber.sendAudio(chunk); }); mic.on('error', (err) => { console.error('Mic error:', err.message); }); process.on('SIGINT', async () => { console.log('\nStopping...'); mic.stop(); await transcriber.close(); process.exit(0); }); console.log('Listening... (Ctrl+C to stop)\n'); }; run().catch(console.error); ``` -------------------------------- ### Full Decibri VAD implementation Source: https://github.com/analyticsinmotion/decibri/blob/main/docs/docs/node/integrations/sherpa-onnx-vad.html A complete example demonstrating initialization, audio processing, and shutdown logic. ```javascript const Decibri = require('decibri'); const sherpa = require('sherpa-onnx'); const config = { sileroVad: { model: './silero_vad.onnx', threshold: 0.5, minSilenceDuration: 0.25, minSpeechDuration: 0.25, windowSize: 512, }, sampleRate: 16000, debug: false, bufferSizeInSeconds: 60, }; const vad = new sherpa.Vad(config); const mic = new Decibri({ sampleRate: 16000, channels: 1 }); const windowSize = 512; let speechActive = false; mic.on('data', (chunk) => { const int16 = new Int16Array(chunk.buffer, chunk.byteOffset, chunk.length / 2); const float32 = new Float32Array(int16.length); for (let i = 0; i < int16.length; i++) { float32[i] = int16[i] / 32768; } for (let offset = 0; offset + windowSize <= float32.length; offset += windowSize) { const window = float32.subarray(offset, offset + windowSize); vad.acceptWaveform(window); if (vad.isSpeechDetected() && !speechActive) { speechActive = true; console.log('[speech start]'); } if (!vad.isSpeechDetected() && speechActive) { speechActive = false; console.log('[speech end]'); } while (!vad.isEmpty()) { const segment = vad.front(); const duration = (segment.samples.length / 16000).toFixed(2); console.log(` segment: ${duration}s of speech`); vad.pop(); } } }); process.on('SIGINT', () => { mic.stop(); vad.free(); process.exit(0); }); console.log('Listening for speech... (Ctrl+C to stop)'); ``` -------------------------------- ### Full OpenAI Realtime API Integration Example Source: https://github.com/analyticsinmotion/decibri/blob/main/docs/docs/node/integrations/openai-realtime.html A complete implementation demonstrating connection, session configuration, audio streaming, and event handling. ```javascript 'use strict'; require('dotenv').config(); const Decibri = require('decibri'); const WebSocket = require('ws'); const API_KEY = process.env.OPENAI_API_KEY; const WS_URL = 'wss://api.openai.com/v1/realtime?intent=transcription'; const run = async () => { const ws = new WebSocket(WS_URL, { headers: { 'Authorization': `Bearer ${API_KEY}`, }, }); ws.on('open', () => { console.log('Connected to OpenAI Realtime API'); // Configure transcription session ws.send(JSON.stringify({ type: 'session.update', session: { type: 'transcription', audio: { input: { transcription: { model: 'gpt-4o-mini-transcribe', }, turn_detection: { type: 'server_vad', threshold: 0.5, silence_duration_ms: 500, prefix_padding_ms: 300, }, }, }, }, })); console.log('Session configured. Opening microphone...\n'); // Important: 24000 Hz, not 16000 Hz. OpenAI Realtime API defaults to 24 kHz. const mic = new Decibri({ sampleRate: 24000, channels: 1 }); mic.on('data', (chunk) => { ws.send(JSON.stringify({ type: 'input_audio_buffer.append', audio: chunk.toString('base64'), })); }); mic.on('error', (err) => { console.error('Mic error:', err.message); }); process.on('SIGINT', () => { console.log('\nStopping...'); mic.stop(); ws.close(); process.exit(0); }); }); ws.on('message', (data) => { const event = JSON.parse(data.toString()); if (event.type === 'conversation.item.input_audio_transcription.completed') { console.log(event.transcript); } if (event.type === 'error') { console.error('Error:', event.error); } }); ws.on('error', (err) => { console.error('WebSocket error:', err.message); }); ws.on('close', (code, reason) => { console.log('Connection closed:', code, reason.toString()); }); }; run().catch(console.error); ``` -------------------------------- ### Configure Environment and Dependencies Source: https://github.com/analyticsinmotion/decibri/blob/main/docs/docs/node/integrations/openai-realtime.html Initial setup for the transcription script, including loading environment variables and initializing the WebSocket and decibri modules. ```javascript require('dotenv').config(); const Decibri = require('decibri'); const WebSocket = require('ws'); const API_KEY = process.env.OPENAI_API_KEY; const WS_URL = 'wss://api.openai.com/v1/realtime?intent=transcription'; ``` -------------------------------- ### Install decibri Source: https://github.com/analyticsinmotion/decibri/blob/main/docs/docs/node/index.html Install the package via npm. ```bash $ npm install decibri ``` -------------------------------- ### Install decibri and AWS SDK Packages Source: https://github.com/analyticsinmotion/decibri/blob/main/docs/docs/node/integrations/aws-transcribe.html Install the decibri library and the AWS Transcribe Streaming client using npm. The dotenv package is optional and used for loading credentials from a .env file. ```bash $ npm install decibri @aws-sdk/client-transcribe-streaming dotenv ``` -------------------------------- ### Full Azure Speech-to-Text Streaming Example with Decibri Source: https://github.com/analyticsinmotion/decibri/blob/main/docs/docs/node/integrations/azure-speech.html A complete Node.js example demonstrating how to set up Azure Speech-to-Text using Decibri. It configures the speech service, microphone input, and handles recognition results, including partial and final transcriptions, cancellations, and session stops. Ensure your Azure Speech service key and region are set in environment variables. ```javascript 'use strict'; require('dotenv').config(); const Decibri = require('decibri'); const sdk = require('microsoft-cognitiveservices-speech-sdk'); async function main() { const speechConfig = sdk.SpeechConfig.fromSubscription( process.env.AZURE_SPEECH_KEY, process.env.AZURE_SPEECH_REGION ); speechConfig.speechRecognitionLanguage = 'en-US'; // Create push stream (default format: 16kHz, 16-bit, mono PCM) const pushStream = sdk.AudioInputStream.createPushStream(); const audioConfig = sdk.AudioConfig.fromStreamInput(pushStream); const recognizer = new sdk.SpeechRecognizer(speechConfig, audioConfig); // Open microphone and push audio to Azure const mic = new Decibri({ sampleRate: 16000, channels: 1 }); mic.on('data', (chunk) => { pushStream.write(chunk.buffer.slice( chunk.byteOffset, chunk.byteOffset + chunk.byteLength )); }); console.log('Azure Speech-to-Text streaming test'); console.log('Speak into your microphone. Press Ctrl+C to stop.\n'); // Handle results recognizer.recognizing = (s, e) => { process.stdout.write(`\r [partial] ${e.result.text} `); }; recognizer.recognized = (s, e) => { if (e.result.reason === sdk.ResultReason.RecognizedSpeech) { console.log(`\n [final] ${e.result.text}`); } }; recognizer.canceled = (s, e) => { if (e.reason === sdk.CancellationReason.Error) { console.error(`Error: ${e.errorDetails}`); } }; recognizer.sessionStopped = (s, e) => { console.log('\nSession stopped.'); }; // Start continuous recognition recognizer.startContinuousRecognitionAsync( () => console.log('Recognition started.\n'), (err) => console.error('Error starting recognition:', err) ); // Clean shutdown process.on('SIGINT', () => { console.log('\nStopping...'); recognizer.stopContinuousRecognitionAsync(() => { recognizer.close(); mic.stop(); pushStream.close(); process.exit(0); }); }); } main().catch(console.error); ``` -------------------------------- ### Install Decibri Package Source: https://github.com/analyticsinmotion/decibri/blob/main/README.md Install the Decibri package using npm. Pre-compiled binaries are included, but it falls back to source compilation if no binary is available for your platform. ```bash npm install decibri ``` -------------------------------- ### Full Decibri Transcription Example Source: https://github.com/analyticsinmotion/decibri/blob/main/docs/docs/node/integrations/whisper-cpp.html This example sets up Decibri to capture audio, buffers it, and transcribes it using whisper.cpp via @kutalia/whisper-node-addon. Configure MODEL_PATH and SAMPLE_RATE according to your needs. Shorter BUFFER_SECONDS provide faster feedback but may reduce accuracy. ```javascript const Decibri = require('decibri'); const { transcribe } = require('@kutalia/whisper-node-addon'); const MODEL_PATH = './ggml-tiny.en.bin'; const SAMPLE_RATE = 16000; const BUFFER_SECONDS = 5; // shorter = faster feedback, longer = better accuracy const mic = new Decibri({ sampleRate: SAMPLE_RATE, channels: 1 }); const chunks = []; let bufferedSamples = 0; const targetSamples = SAMPLE_RATE * BUFFER_SECONDS; let processing = false; async function processBuffer() { if (processing) return; processing = true; const pcm16 = Buffer.concat(chunks); chunks.length = 0; bufferedSamples = 0; const int16 = new Int16Array(pcm16.buffer, pcm16.byteOffset, pcm16.length / 2); const float32 = new Float32Array(int16.length); for (let i = 0; i < int16.length; i++) { float32[i] = int16[i] / 32768; } const result = await transcribe({ pcmf32: float32, model: MODEL_PATH, language: 'en', // use 'auto' with multilingual models (e.g. ggml-base.bin) no_timestamps: true, }); // transcription may be nested arrays, so flatten to a single string const text = result.transcription.flat().join(' ').trim(); if (text) console.log(text); processing = false; } mic.on('data', (chunk) => { chunks.push(chunk); bufferedSamples += chunk.length / 2; if (bufferedSamples >= targetSamples) { processBuffer(); } }); process.on('SIGINT', async () => { mic.stop(); if (chunks.length > 0) await processBuffer(); process.exit(0); }); console.log('Listening... (Ctrl+C to stop)'); ``` -------------------------------- ### Install decibri and Mistral AI Packages Source: https://github.com/analyticsinmotion/decibri/blob/main/docs/docs/node/integrations/mistral-voxtral.html Install the necessary npm packages for decibri, Mistral AI SDK, and dotenv for environment variable management. ```bash $ npm install decibri @mistralai/mistralai dotenv ``` -------------------------------- ### Full AWS Transcribe Streaming Example Source: https://github.com/analyticsinmotion/decibri/blob/main/docs/docs/node/integrations/aws-transcribe.html A complete example demonstrating real-time transcription using Decibri and AWS SDK v3. Requires AWS credentials and configuration. ```javascript 'use strict'; require('dotenv').config(); const Decibri = require('decibri'); const { TranscribeStreamingClient, StartStreamTranscriptionCommand, } = require('@aws-sdk/client-transcribe-streaming'); // ── Audio stream generator ────────────────────────────────── function createAudioStream(mic) { const chunks = []; let done = false; let resolve; mic.on('data', (chunk) => { chunks.push(chunk); if (resolve) { resolve(); resolve = null; } }); mic.on('end', () => { done = true; if (resolve) { resolve(); resolve = null; } }); return { [Symbol.asyncIterator]() { return { async next() { while (chunks.length === 0 && !done) { await new Promise((r) => { resolve = r; }); } if (chunks.length > 0) { return { value: { AudioEvent: { AudioChunk: chunks.shift() } }, done: false }; } return { done: true }; }, }; }, }; } // ── Main ──────────────────────────────────────────────────── async function main() { const client = new TranscribeStreamingClient({ region: process.env.AWS_REGION || 'us-east-1', }); const mic = new Decibri({ sampleRate: 16000, channels: 1 }); console.log('Starting transcription. Speak into your microphone...'); console.log('Press Ctrl+C to stop.\n'); const command = new StartStreamTranscriptionCommand({ LanguageCode: 'en-US', MediaEncoding: 'pcm', MediaSampleRateHertz: '16000', AudioStream: createAudioStream(mic), }); const response = await client.send(command); for await (const event of response.TranscriptResultStream) { if (event.TranscriptEvent) { const results = event.TranscriptEvent.Transcript.Results; for (const result of results) { const transcript = result.Alternatives[0].Transcript; if (result.IsPartial) { process.stdout.write(`\r [partial] ${transcript} `); } else { console.log(`\n [final] ${transcript}`); } } } } } // ── Cleanup on Ctrl+C ────────────────────────────────────── process.on('SIGINT', () => { console.log('\nStopping...'); process.exit(0); }); main().catch(console.error); ``` -------------------------------- ### Full Speech Recognition Example Source: https://github.com/analyticsinmotion/decibri/blob/main/docs/docs/node/integrations/sherpa-onnx-stt.html A complete implementation combining model configuration, stream initialization, audio processing, and shutdown handling. ```javascript const Decibri = require('decibri'); const sherpa = require('sherpa-onnx'); const modelDir = './sherpa-onnx-streaming-zipformer-en-20M-2023-02-17'; const config = { featConfig: { sampleRate: 16000, featureDim: 80 }, modelConfig: { transducer: { encoder: `${modelDir}/encoder-epoch-99-avg-1.onnx`, decoder: `${modelDir}/decoder-epoch-99-avg-1.onnx`, joiner: `${modelDir}/joiner-epoch-99-avg-1.onnx`, }, tokens: `${modelDir}/tokens.txt`, numThreads: 2, provider: 'cpu', modelType: 'zipformer', }, }; const recognizer = new sherpa.OnlineRecognizer(config); const stream = recognizer.createStream(); const mic = new Decibri({ sampleRate: 16000, channels: 1 }); let lastText = ''; mic.on('data', (chunk) => { const int16 = new Int16Array(chunk.buffer, chunk.byteOffset, chunk.length / 2); const float32 = new Float32Array(int16.length); for (let i = 0; i < int16.length; i++) { float32[i] = int16[i] / 32768; } stream.acceptWaveform(16000, float32); while (recognizer.isReady(stream)) { recognizer.decode(stream); } const text = recognizer.getResult(stream).text.trim(); if (text && text !== lastText) { lastText = text; process.stdout.write('\r' + text); } }); process.on('SIGINT', () => { mic.stop(); const finalText = recognizer.getResult(stream).text.trim(); if (finalText) console.log('\n' + finalText); stream.free(); recognizer.free(); process.exit(0); }); console.log('Listening... (Ctrl+C to stop)'); ``` -------------------------------- ### Install Decibri and Whisper Addon Source: https://github.com/analyticsinmotion/decibri/blob/main/docs/docs/node/integrations/whisper-cpp.html Install the necessary npm packages for Decibri and the Whisper.cpp Node.js addon. This is the first step to enable local speech-to-text transcription. ```bash npm install decibri @kutalia/whisper-node-addon ``` -------------------------------- ### Install Linux Build Dependencies Source: https://github.com/analyticsinmotion/decibri/blob/main/README.md Installs necessary build tools and libraries on Debian-based Linux systems for compiling Decibri. ```bash sudo apt-get install -y build-essential libasound2-dev ``` -------------------------------- ### Install macOS Build Dependencies Source: https://github.com/analyticsinmotion/decibri/blob/main/README.md Installs Xcode command-line tools on macOS, which are required for building native Node.js addons. ```bash xcode-select --install ``` -------------------------------- ### Full Realtime Transcription Example Source: https://github.com/analyticsinmotion/decibri/blob/main/docs/docs/node/integrations/mistral-voxtral.html A complete implementation for streaming microphone audio to the Mistral realtime transcription service. ```javascript import 'dotenv/config'; import Decibri from 'decibri'; import { RealtimeTranscription, AudioEncoding } from '@mistralai/mistralai/extra/realtime'; const API_KEY = process.env.MISTRAL_API_KEY; const MODEL = 'voxtral-mini-transcribe-realtime-2602'; const audioFormat = { encoding: AudioEncoding.PcmS16le, sampleRate: 16000, }; async function* createAudioStream() { const mic = new Decibri({ sampleRate: 16000, channels: 1 }); console.log('Listening... Speak into your microphone. (Ctrl+C to stop)'); try { for await (const chunk of mic) { yield new Uint8Array(chunk); } } finally { mic.stop(); } } const client = new RealtimeTranscription({ apiKey: API_KEY }); const audioStream = createAudioStream(); try { for await (const event of client.transcribeStream( audioStream, MODEL, { audioFormat } )) { if (event.type === 'transcription.text.delta') { process.stdout.write(event.text); } else if (event.type === 'transcription.done') { process.stdout.write('\n'); break; } else if (event.type === 'error') { const msg = typeof event.error.message === 'string' ? event.error.message : JSON.stringify(event.error.message); console.error('\nError:', msg); break; } } } finally { await audioStream.return?.(); } ``` -------------------------------- ### TypeScript example with Decibri Source: https://github.com/analyticsinmotion/decibri/blob/main/README.md Demonstrates Decibri usage in TypeScript, including type definitions for options and device info. Shows how to access raw audio samples as an Int16Array. ```typescript import Decibri, { DeviceInfo, DecibriOptions } from 'decibri'; const options: DecibriOptions = { sampleRate: 16000, channels: 1 }; const mic = new Decibri(options); mic.on('data', (chunk: Buffer) => { // zero-copy Int16 view over the same memory const samples = new Int16Array(chunk.buffer, chunk.byteOffset, chunk.length / 2); }); mic.on('backpressure', () => console.warn('Consumer too slow')); const devices: DeviceInfo[] = Decibri.devices(); ``` -------------------------------- ### Constructor: new Decibri(options?) Source: https://github.com/analyticsinmotion/decibri/blob/main/docs/docs/browser/api-reference.html Creates a new capture instance. Does not start capture automatically. ```APIDOC ## Constructor: new Decibri(options?) ### Description Creates a new capture instance. Does not start capture. Call `start()` to begin. ### Parameters #### Request Body - **sampleRate** (number) - Optional - Target sample rate in Hz (1,000 to 384,000). Default: 16000 - **channels** (number) - Optional - Number of channels. Default: 1 - **framesPerBuffer** (number) - Optional - Frames per chunk. Default: 1600 - **device** (string) - Optional - deviceId string from Decibri.devices(). Default: system default - **format** ('int16' | 'float32') - Optional - Sample encoding format. Default: 'int16' - **vad** (boolean) - Optional - Enable voice activity detection. Default: false - **vadThreshold** (number) - Optional - RMS energy threshold for speech detection (0 to 1). Default: 0.01 - **vadHoldoff** (number) - Optional - Milliseconds of sub-threshold audio before 'silence' is emitted. Default: 300 - **echoCancellation** (boolean) - Optional - Browser echo cancellation. Default: true - **noiseSuppression** (boolean) - Optional - Browser noise suppression. Default: true - **workletUrl** (string) - Optional - URL for AudioWorklet processor file. ``` -------------------------------- ### Capture Microphone Audio in Node.js Source: https://github.com/analyticsinmotion/decibri/blob/main/docs/index.html Basic steps to install, initialize, and stream audio data using the decibri library. ```bash npm install decibri ``` ```javascript const Decibri = require('decibri'); ``` ```javascript const mic = new Decibri({ sampleRate: 16000, channels: 1 }); ``` ```javascript mic.on('data', (chunk) => { /* process PCM audio buffer */ }); ``` ```javascript mic.stop(); ``` -------------------------------- ### Clone and Build Decibri Project Source: https://github.com/analyticsinmotion/decibri/blob/main/README.md Clones the Decibri repository with submodules, installs Node.js dependencies, and builds the project. Ensure Node.js >= 18 and platform build tools are installed. ```bash git clone --recurse-submodules https://github.com/analyticsinmotion/decibri.git cd decibri npm install npm run build ``` -------------------------------- ### Initialize Decibri Instance Source: https://github.com/analyticsinmotion/decibri/blob/main/docs/docs/browser/api-reference.html Create a new capture instance using the Decibri constructor. Note that this does not start the capture process automatically. ```javascript import { Decibri } from 'decibri-web'; const mic = new Decibri(options?); ``` -------------------------------- ### Pipe Audio to WAV File with Decibri Source: https://context7.com/analyticsinmotion/decibri/llms.txt Capture audio and pipe it to a file as a WAV format. This example includes a helper function to build the WAV header correctly. ```javascript const fs = require('fs'); const Decibri = require('decibri'); const SAMPLE_RATE = 16000; const CHANNELS = 1; const BITS_PER_SAMPLE = 16; const DURATION_MS = 5000; const mic = new Decibri({ sampleRate: SAMPLE_RATE, channels: CHANNELS }); const chunks = []; mic.on('data', (chunk) => chunks.push(chunk)); mic.on('error', (err) => { console.error('Mic error:', err.message); process.exit(1); }); console.log(`Recording for ${DURATION_MS / 1000} seconds...`); setTimeout(() => { mic.stop(); const pcm = Buffer.concat(chunks); const header = buildWavHeader(pcm.length, SAMPLE_RATE, CHANNELS, BITS_PER_SAMPLE); fs.writeFileSync('capture.wav', Buffer.concat([header, pcm])); console.log(`Wrote capture.wav (${(pcm.length / 1024).toFixed(1)} KB PCM)`); }, DURATION_MS); function buildWavHeader(dataBytes, sampleRate, channels, bitsPerSample) { const byteRate = sampleRate * channels * bitsPerSample / 8; const blockAlign = channels * bitsPerSample / 8; const buf = Buffer.alloc(44); buf.write('RIFF', 0); buf.writeUInt32LE(36 + dataBytes, 4); buf.write('WAVE', 8); buf.write('fmt ', 12); buf.writeUInt32LE(16, 16); // fmt chunk size buf.writeUInt16LE(1, 20); // PCM format buf.writeUInt16LE(channels, 22); buf.writeUInt32LE(sampleRate, 24); buf.writeUInt32LE(byteRate, 28); buf.writeUInt16LE(blockAlign, 32); buf.writeUInt16LE(bitsPerSample, 34); buf.write('data', 36); buf.writeUInt32LE(dataBytes, 40); return buf; } ``` -------------------------------- ### Restart Microphone Capture Source: https://github.com/analyticsinmotion/decibri/blob/main/docs/docs/browser/index.html To restart capture after stopping, call 'start()' again. This will create a fresh audio pipeline. ```javascript await mic.start(); ``` -------------------------------- ### Start Continuous Speech Recognition Source: https://github.com/analyticsinmotion/decibri/blob/main/docs/docs/node/integrations/azure-speech.html Initiate continuous recognition using startContinuousRecognitionAsync(). This method is suitable for ongoing audio input from a microphone. ```javascript recognizer.startContinuousRecognitionAsync(); ``` -------------------------------- ### Binary Distribution Path Convention Source: https://github.com/analyticsinmotion/decibri/blob/main/AGENTS.md Defines the binary path convention for distribution: `prebuilds/{platform}-{arch}/node.napi.node`. This must be consistent across package.json, .github/workflows/prebuild.yml, and the install script. ```text prebuilds/{platform}-{arch}/node.napi.node ``` -------------------------------- ### List Available Audio Input Devices Source: https://context7.com/analyticsinmotion/decibri/llms.txt Use the static `Decibri.devices()` method to get an array of available audio input devices. Each device object includes its index, name, maximum channels, default sample rate, and whether it's the system default. This information can be used to select a specific device when initializing Decibri. ```javascript const Decibri = require('decibri'); const devices = Decibri.devices(); console.log('Available input devices:'); devices.forEach(d => { console.log(` [${d.index}] ${d.name}`); console.log(` Channels: ${d.maxInputChannels}, Sample rate: ${d.defaultSampleRate}Hz${d.isDefault ? ' (default)' : ''}`); }); // Output example: // Available input devices: // [0] Built-in Microphone // Channels: 1, Sample rate: 44100Hz (default) // [1] USB Audio Device // Channels: 2, Sample rate: 48000Hz // Use a specific device by index const mic = new Decibri({ device: 1 }); // Or by name substring (case-insensitive) const usbMic = new Decibri({ device: 'usb' }); ``` -------------------------------- ### Initialize Decibri Microphone Stream Source: https://context7.com/analyticsinmotion/decibri/llms.txt Instantiate Decibri with default or custom options to start capturing audio. Options include sample rate, channels, buffer size, device selection, audio format, and VAD settings. Listen for 'data', 'error', and 'backpressure' events. ```javascript const Decibri = require('decibri'); // Basic usage with defaults (16kHz, mono, 100ms chunks) const mic = new Decibri(); // Custom configuration const mic = new Decibri({ sampleRate: 16000, // Samples per second (1000-384000) channels: 1, // Input channels (1-32) framesPerBuffer: 1600, // Frames per callback (64-65536), 1600 = 100ms at 16kHz device: 'USB Microphone', // Device name substring or index from Decibri.devices() format: 'int16', // 'int16' (default) or 'float32' vad: true, // Enable voice activity detection vadThreshold: 0.01, // RMS energy threshold for speech (0-1) vadHoldoff: 300 // Silence delay in ms before 'silence' event }); mic.on('data', (chunk) => { // chunk is a Buffer of PCM samples // For int16: each sample is 2 bytes, little-endian // Zero-copy typed array access: const samples = new Int16Array(chunk.buffer, chunk.byteOffset, chunk.length / 2); console.log(`Received ${samples.length} samples, peak: ${Math.max(...samples.map(Math.abs))}`); }); mic.on('error', (err) => { console.error('Microphone error:', err.message); }); mic.on('backpressure', () => { console.warn('Consumer too slow - consider dropping frames'); }); // Stop after 10 seconds setTimeout(() => mic.stop(), 10000); ``` -------------------------------- ### Test Prebuilt Binary Loading Source: https://github.com/analyticsinmotion/decibri/blob/main/AGENTS.md Steps to test prebuilt binary loading, useful after toolchain, loader, or binding.gyp changes. This involves copying the built node.napi.node to a prebuilds directory and running tests. ```bash mkdir -p prebuilds/win32-x64 cp build/Release/decibri.node prebuilds/win32-x64/node.napi.node mv build build_backup node test/basic.js mv build_backup build rm -r prebuilds ``` -------------------------------- ### Select Microphone Device Source: https://github.com/analyticsinmotion/decibri/blob/main/docs/docs/node/index.html List available input devices and initialize the microphone by index or name substring. ```javascript const Decibri = require('decibri'); // List all input devices const devices = Decibri.devices(); console.log(devices); // Select by index const mic = new Decibri({ device: 2, sampleRate: 16000, channels: 1 }); // Or select by name substring (case-insensitive) const mic2 = new Decibri({ device: 'USB', sampleRate: 16000, channels: 1 }); ``` -------------------------------- ### Initialize Google Cloud Client Source: https://github.com/analyticsinmotion/decibri/blob/main/docs/docs/node/integrations/google-speech.html Import required modules and initialize the SpeechClient. ```javascript 'use strict'; require('dotenv').config(); const Decibri = require('decibri'); const speech = require('@google-cloud/speech'); const client = new speech.SpeechClient(); ``` -------------------------------- ### Initialize KWS engine Source: https://github.com/analyticsinmotion/decibri/blob/main/docs/docs/node/integrations/sherpa-onnx-kws.html Create the keyword spotter instance and a detection stream. ```javascript const kws = new sherpa.KeywordSpotter(config); const stream = kws.createStream(); ``` -------------------------------- ### Get Library Version Source: https://github.com/analyticsinmotion/decibri/blob/main/docs/docs/browser/api-reference.html Retrieve the current version information for the decibri-web package. ```javascript Decibri.version(); // { decibriWeb: '0.1.0' } ``` -------------------------------- ### Connect and Initialize Microphone Source: https://github.com/analyticsinmotion/decibri/blob/main/docs/docs/node/integrations/assemblyai.html Establish the connection to AssemblyAI and initialize the Decibri microphone instance. Audio transmission should only commence after the connection is established. ```javascript await transcriber.connect(); const mic = new Decibri({ sampleRate: 16000, channels: 1 }); ``` -------------------------------- ### Get Library Version Source: https://github.com/analyticsinmotion/decibri/blob/main/docs/docs/node/api-reference.html Returns version information for both the decibri package and the underlying PortAudio library. ```javascript Decibri.version(); // { decibri: '1.0.0', portaudio: 'PortAudio V19.7.0-devel...' } ``` -------------------------------- ### Static Methods: Decibri.devices() and Decibri.version() Source: https://github.com/analyticsinmotion/decibri/blob/main/docs/docs/browser/api-reference.html Static utility methods for device discovery and version checking. ```APIDOC ## Decibri.devices() ### Description Lists available audio input devices. ### Response - **Promise** - Returns an array of device objects containing deviceId, label, and groupId. ## Decibri.version() ### Description Returns version information for decibri-web. ### Response - **VersionInfo** - Object containing the current version string. ``` -------------------------------- ### Configure AssemblyAI Client Source: https://github.com/analyticsinmotion/decibri/blob/main/docs/docs/node/integrations/assemblyai.html Initializes the AssemblyAI client using an API key loaded from a .env file. ```javascript require('dotenv').config(); const Decibri = require('decibri'); const { AssemblyAI } = require('assemblyai'); const client = new AssemblyAI({ apiKey: process.env.ASSEMBLYAI_API_KEY }); ``` -------------------------------- ### Initialize Decibri and Handle Audio Data in TypeScript Source: https://context7.com/analyticsinmotion/decibri/llms.txt Demonstrates how to initialize Decibri with custom options, listen for audio data chunks, and process them as Int16 samples. Includes event handlers for speech, silence, backpressure, and errors. Requires importing Decibri and related types. ```typescript import Decibri, { DeviceInfo, DecibriOptions, VersionInfo } from 'decibri'; const options: DecibriOptions = { sampleRate: 16000, channels: 1, vad: true, vadThreshold: 0.02, vadHoldoff: 500 }; const mic = new Decibri(options); mic.on('data', (chunk: Buffer) => { // Zero-copy Int16 view over the same memory const samples = new Int16Array(chunk.buffer, chunk.byteOffset, chunk.length / 2); console.log(`Samples: ${samples.length}`); }); mic.on('speech', () => console.log('Speech detected')); mic.on('silence', () => console.log('Silence detected')); mic.on('backpressure', () => console.warn('Consumer too slow')); mic.on('error', (err: Error) => console.error(err.message)); const devices: DeviceInfo[] = Decibri.devices(); const version: VersionInfo = Decibri.version(); setTimeout(() => mic.stop(), 10000); ``` -------------------------------- ### Initialize Microphone Instance Source: https://github.com/analyticsinmotion/decibri/blob/main/docs/docs/node/integrations/whisper-cpp.html Create a Decibri instance configured for 16 kHz mono audio input. ```javascript const mic = new Decibri({ sampleRate: SAMPLE_RATE, channels: 1 }); ``` -------------------------------- ### Get Version Information Source: https://context7.com/analyticsinmotion/decibri/llms.txt A static method to retrieve version information for the decibri package and the bundled PortAudio library. ```APIDOC ## Decibri.version() ### Description Static method that returns version information for the decibri package and the bundled PortAudio library. ### Method `Decibri.version()` ### Response - **versionInfo** (object) - **decibri** (string) - The version of the decibri package. - **portaudio** (string) - The version of the bundled PortAudio library. ### Request Example ```javascript const Decibri = require('decibri'); const info = Decibri.version(); console.log(`decibri: ${info.decibri}`); console.log(`PortAudio: ${info.portaudio}`); ``` ``` -------------------------------- ### Constructor: new Decibri(options?) Source: https://github.com/analyticsinmotion/decibri/blob/main/README.md Initializes a new microphone capture stream with configurable audio parameters. ```APIDOC ## new Decibri(options?) ### Description Creates a Readable stream that captures from the system default microphone. ### Parameters #### Request Body - **sampleRate** (number) - Optional - Samples per second (1000–384000). Default: 16000 - **channels** (number) - Optional - Number of input channels (1–32). Default: 1 - **framesPerBuffer** (number) - Optional - Frames per audio callback (64–65536). Default: 1600 - **device** (number | string) - Optional - Device index or case-insensitive name substring. Default: system default - **format** ('int16' | 'float32') - Optional - Sample encoding. Default: 'int16' - **vad** (boolean) - Optional - Enable voice activity detection. Default: false - **vadThreshold** (number) - Optional - RMS energy threshold for speech (0–1). Default: 0.01 - **vadHoldoff** (number) - Optional - Silence holdoff in ms before 'silence' is emitted. Default: 300 ``` -------------------------------- ### Build Native Addon Source: https://github.com/analyticsinmotion/decibri/blob/main/AGENTS.md Command to build the native addon from source using npm. ```bash npm run build ``` -------------------------------- ### Stop Microphone Capture Source: https://github.com/analyticsinmotion/decibri/blob/main/docs/docs/browser/index.html Call the 'stop()' method to release all resources, including MediaStream tracks and the AudioContext. This is safe to call multiple times or before 'start()'. ```javascript mic.stop(); ``` -------------------------------- ### Initialize Theme from Local Storage or System Preference Source: https://github.com/analyticsinmotion/decibri/blob/main/docs/docs/browser/index.html This script initializes the theme of the document based on 'decibri-theme' in localStorage or the user's system preference for color scheme. ```javascript (function() { var t = localStorage.getItem('decibri-theme'); if (t) document.documentElement.setAttribute('data-theme', t); else if (window.matchMedia && window.matchMedia('(prefers-color-scheme: light)').matches) document.documentElement.setAttribute('data-theme', 'light'); })(); ``` -------------------------------- ### Run Static Tests Source: https://github.com/analyticsinmotion/decibri/blob/main/CONTRIBUTING.md Execute static tests to verify that the module loads correctly and the API surface is as expected. These tests do not require a connected microphone. ```bash npm test node test/float32.js ``` -------------------------------- ### Get available audio devices Source: https://github.com/analyticsinmotion/decibri/blob/main/README.md Retrieves a list of all available audio input devices on the system. Each device object contains its index, name, and channel capabilities. ```javascript const devices = Decibri.devices(); // [ // { index: 0, name: 'Built-in Microphone', maxInputChannels: 1, defaultSampleRate: 44100, isDefault: true }, // ... // ] ``` -------------------------------- ### Minimal IAM Policy for Transcribe Source: https://github.com/analyticsinmotion/decibri/blob/main/docs/docs/node/integrations/aws-transcribe.html This IAM policy grants the necessary permission to start streaming transcription. It is recommended for production environments to follow the principle of least privilege. ```json { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": "transcribe:StartStreamTranscription", "Resource": "*" } ] } ``` -------------------------------- ### Static Method: Decibri.devices() Source: https://github.com/analyticsinmotion/decibri/blob/main/docs/docs/node/api-reference.html Returns an array of available audio input devices on the system, including their properties. ```APIDOC ## Static Method: Decibri.devices() ### Description Returns an array of available audio input devices on the system. ### Response Example ```json [ { "index": 0, "name": "Built-in Microphone", "maxInputChannels": 1, "defaultSampleRate": 44100, "isDefault": true } ] ``` Each device object contains: Property | Type | Description ---------|------|------------ `index` | `number` | PortAudio device index, used as `options.device` `name` | `string` | Human-readable device name reported by the OS `maxInputChannels` | `number` | Maximum number of input channels supported `defaultSampleRate` | `number` | Device's native/preferred sample rate in Hz `isDefault` | `boolean` | Whether this is the current system default input device ```