### Complete Audio Record and Playback Example in JavaScript Source: https://context7.com/saeta-eth/node-cpal/llms.txt A comprehensive example demonstrating recording audio from the default input device for a specified duration and then playing it back through the default output device. It handles channel adaptation and stream management. ```javascript const cpal = require('node-cpal'); async function recordAndPlayback() { // Get default devices const inputDevice = cpal.getDefaultInputDevice(); const outputDevice = cpal.getDefaultOutputDevice(); // Get configurations const inputConfig = cpal.getDefaultInputConfig(inputDevice.deviceId); const outputConfig = cpal.getDefaultOutputConfig(outputDevice.deviceId); // Record audio const recordedChunks = []; const RECORD_DURATION = 5; // seconds console.log(`Recording ${RECORD_DURATION} seconds...`); const inputStream = cpal.createStream( inputDevice.deviceId, true, inputConfig, (data) => { recordedChunks.push(new Float32Array(data)); } ); await new Promise((resolve) => setTimeout(resolve, RECORD_DURATION * 1000)); cpal.closeStream(inputStream); // Playback recorded audio console.log('Playing back...'); const outputStream = cpal.createStream( outputDevice.deviceId, false, outputConfig, () => {} ); // Adapt mono to stereo if needed function adaptChannels(monoData, outputChannels) { if (outputChannels === 1) return monoData; const stereoData = new Float32Array(monoData.length * outputChannels); for (let i = 0; i < monoData.length; i++) { for (let ch = 0; ch < outputChannels; ch++) { stereoData[i * outputChannels + ch] = monoData[i]; } } return stereoData; } for (const chunk of recordedChunks) { const adaptedChunk = adaptChannels(chunk, outputConfig.channels); cpal.writeToStream(outputStream, adaptedChunk); const delayMs = (chunk.length / inputConfig.sampleRate) * 1000; await new Promise((resolve) => setTimeout(resolve, delayMs)); } await new Promise((resolve) => setTimeout(resolve, 500)); cpal.closeStream(outputStream); console.log('Done!'); } recordAndPlayback(); ``` -------------------------------- ### Build Project (Bash) Source: https://github.com/saeta-eth/node-cpal/blob/main/README.md Commands to build the Node-CPAL project from source. This includes installing dependencies and running the build script. ```bash npm install npm run build ``` -------------------------------- ### Install node-cpal Package Source: https://github.com/saeta-eth/node-cpal/blob/main/README.md Installs the node-cpal package using npm. This is the first step to integrate cross-platform audio capabilities into your Node.js application. ```bash npm install node-cpal ``` -------------------------------- ### Get Supported Input Configurations Source: https://context7.com/saeta-eth/node-cpal/llms.txt Fetches the supported input configurations for a given audio device, identified by its device ID. The output details the sample rate ranges, channel counts, and sample formats ('i16', 'u16', or 'f32') that the device can handle for recording. ```javascript const cpal = require('node-cpal'); const inputDevice = cpal.getDefaultInputDevice(); const configs = cpal.getSupportedInputConfigs(inputDevice.deviceId); configs.forEach((config, index) => { console.log(`Config #${index + 1}:`); console.log(` Sample Rate Range: ${config.minSampleRate} - ${config.maxSampleRate} Hz`); console.log(` Channels: ${config.channels}`); console.log(` Format: ${config.sampleFormat}`); // 'i16', 'u16', or 'f32' }); ``` -------------------------------- ### Get Supported Output Audio Configurations Source: https://github.com/saeta-eth/node-cpal/blob/main/README.md Fetches and returns all supported audio output configurations for a given audio device. This allows selection of appropriate settings for audio playback. ```javascript const cpal = require('node-cpal'); const outputDevice = cpal.getDefaultOutputDevice(); const configs = cpal.getSupportedOutputConfigs(outputDevice); ``` -------------------------------- ### Get Supported Output Configurations Source: https://context7.com/saeta-eth/node-cpal/llms.txt Retrieves the supported output configurations for a specified audio device using its device ID. The function returns an array detailing the compatible sample rate ranges, number of channels, and audio sample formats for playback. ```javascript const cpal = require('node-cpal'); const outputDevice = cpal.getDefaultOutputDevice(); const configs = cpal.getSupportedOutputConfigs(outputDevice.deviceId); configs.forEach((config, index) => { console.log(`Config #${index + 1}:`); console.log(` Sample Rate Range: ${config.minSampleRate} - ${config.maxSampleRate} Hz`); console.log(` Channels: ${config.channels}`); console.log(` Format: ${config.sampleFormat}`); }); ``` -------------------------------- ### Get Audio Devices Source: https://context7.com/saeta-eth/node-cpal/llms.txt Fetches all available audio devices for a specified host or across all hosts if none is specified. Each device object contains its name, unique IDs, default status, and supported audio configurations. This is useful for selecting specific audio hardware for input or output. ```javascript const cpal = require('node-cpal'); // Get devices from the default host const devices = cpal.getDevices(); devices.forEach((device) => { console.log(`Device: ${device.name}`); console.log(` ID: ${device.deviceId}`); console.log(` Host: ${device.hostId}`); console.log(` Default Input: ${device.isDefaultInput ? 'Yes' : 'No'}`); console.log(` Default Output: ${device.isDefaultOutput ? 'Yes' : 'No'}`); // Show supported output configurations if (device.supportedOutputConfigs) { device.supportedOutputConfigs.forEach((config, index) => { console.log(` Output Config #${index + 1}: ${config.minSampleRate}-${config.maxSampleRate} Hz, ${config.channels} channels, ${config.sampleFormat}`); }); } }); ``` -------------------------------- ### Get All Available Audio Hosts Source: https://github.com/saeta-eth/node-cpal/blob/main/README.md Retrieves and logs a list of all audio hosts available on the system. This is useful for understanding the different audio backends the system supports. ```javascript const cpal = require('node-cpal'); const hosts = cpal.getHosts(); // Example: ['CoreAudio'] ``` -------------------------------- ### Get All Audio Devices Source: https://github.com/saeta-eth/node-cpal/blob/main/README.md Retrieves and logs a list of all audio devices. If a host ID is provided, it lists devices for that specific host; otherwise, it defaults to the default host. ```javascript const cpal = require('node-cpal'); const devices = cpal.getDevices(); ``` -------------------------------- ### Get Supported Input Audio Configurations Source: https://github.com/saeta-eth/node-cpal/blob/main/README.md Fetches and returns all supported audio input configurations for a given audio device. This includes details like sample rates, channels, and data formats. ```javascript const cpal = require('node-cpal'); const inputDevice = cpal.getDefaultInputDevice(); const configs = cpal.getSupportedInputConfigs(inputDevice); ``` -------------------------------- ### Get Audio Hosts Source: https://context7.com/saeta-eth/node-cpal/llms.txt Retrieves a list of available audio hosts on the system. Audio hosts are platform-specific audio backends like CoreAudio, WASAPI, ALSA, or JACK. The output includes the ID and name of each host. ```javascript const cpal = require('node-cpal'); const hosts = cpal.getHosts(); // Output: [{ id: 'CoreAudio', name: 'CoreAudio' }] hosts.forEach((host) => { console.log(`Host: ${host.name} (ID: ${host.id})`); }); ``` -------------------------------- ### Get Default Input Configuration (JavaScript) Source: https://github.com/saeta-eth/node-cpal/blob/main/README.md Retrieves the default audio input configuration for a specified device. This configuration includes sample rate, channels, and audio format. ```javascript const inputDevice = cpal.getDefaultInputDevice(); const config = cpal.getDefaultInputConfig(inputDevice); ``` -------------------------------- ### Get Default Output Configuration (JavaScript) Source: https://github.com/saeta-eth/node-cpal/blob/main/README.md Retrieves the default audio output configuration for a specified device. This configuration includes sample rate, channels, and audio format. ```javascript const outputDevice = cpal.getDefaultOutputDevice(); const config = cpal.getDefaultOutputConfig(outputDevice); ``` -------------------------------- ### Get Default Output Audio Device Source: https://github.com/saeta-eth/node-cpal/blob/main/README.md Retrieves the device ID for the system's default audio output (playback) device. This is typically the speakers or headphones. ```javascript const cpal = require('node-cpal'); const outputDevice = cpal.getDefaultOutputDevice(); ``` -------------------------------- ### Get Default Input Audio Device Source: https://github.com/saeta-eth/node-cpal/blob/main/README.md Retrieves the device ID for the system's default audio input (recording) device. This is commonly used for microphone access. ```javascript const cpal = require('node-cpal'); const inputDevice = cpal.getDefaultInputDevice(); ``` -------------------------------- ### Get Default Input Device Source: https://context7.com/saeta-eth/node-cpal/llms.txt Retrieves the default audio input (recording) device. The function returns a detailed device object, including its name, ID, host ID, and a list of its supported input configurations. Handles cases where no input device is available. ```javascript const cpal = require('node-cpal'); try { const inputDevice = cpal.getDefaultInputDevice(); console.log(`Default Input Device: ${inputDevice.name}`); console.log(`Device ID: ${inputDevice.deviceId}`); console.log(`Host ID: ${inputDevice.hostId}`); // Check supported input configurations if (inputDevice.supportedInputConfigs) { inputDevice.supportedInputConfigs.forEach((config) => { console.log(` Sample Rate: ${config.minSampleRate}-${config.maxSampleRate} Hz`); console.log(` Channels: ${config.channels}`); console.log(` Format: ${config.sampleFormat}`); }); } } catch (error) { console.error('No input device available:', error.message); } ``` -------------------------------- ### Get Default Output Device Source: https://context7.com/saeta-eth/node-cpal/llms.txt Retrieves the default audio output (playback) device. The function returns a detailed device object, including its name, ID, and host ID. It includes error handling for scenarios where no output device is found. ```javascript const cpal = require('node-cpal'); try { const outputDevice = cpal.getDefaultOutputDevice(); console.log(`Default Output Device: ${outputDevice.name}`); console.log(`Device ID: ${outputDevice.deviceId}`); console.log(`Host ID: ${outputDevice.hostId}`); } catch (error) { console.error('No output device available:', error.message); } ``` -------------------------------- ### Run Tests (Bash) Source: https://github.com/saeta-eth/node-cpal/blob/main/README.md Command to execute the test suite for the Node-CPAL project. This ensures the library functions as expected. ```bash npm test ``` -------------------------------- ### Basic node-cpal Usage: Audio Device and Stream Management Source: https://github.com/saeta-eth/node-cpal/blob/main/README.md Demonstrates fundamental usage of the node-cpal library. It shows how to retrieve available audio hosts, identify the default output device, and create a basic audio output stream. The stream is subsequently closed. ```javascript const cpal = require('node-cpal'); // List all available audio hosts const hosts = cpal.getHosts(); console.log('Available audio hosts:', hosts); // Get the default output device const outputDevice = cpal.getDefaultOutputDevice(); console.log('Default output device:', outputDevice); // Create an output stream with default configuration const config = cpal.getDefaultOutputConfig(outputDevice.deviceId); const stream = cpal.createStream( outputDevice.deviceId, false, // false for output stream, true for input stream config, () => {} // Callback function (not needed for output streams) ); // Close the stream when done cpal.closeStream(stream); ``` -------------------------------- ### Contribute to Project (Bash) Source: https://github.com/saeta-eth/node-cpal/blob/main/README.md Steps for contributing to the Node-CPAL project, including forking, creating branches, committing changes, and opening pull requests. ```bash git checkout -b feature/amazing-feature git commit -m 'Add some amazing feature' git push origin feature/amazing-feature ``` -------------------------------- ### Input/Output Configuration Source: https://github.com/saeta-eth/node-cpal/blob/main/README.md Provides functions to retrieve the default input and output configurations for a given audio device. ```APIDOC ## GET /cpal/config/input ### Description Retrieves the default input configuration for a specified audio device. ### Method GET ### Endpoint `/cpal/config/input` ### Parameters #### Query Parameters - **deviceId** (string) - Required - The identifier of the audio device. ### Response #### Success Response (200) - **sampleRate** (number) - The sample rate of the audio stream. - **channels** (number) - The number of audio channels. - **format** ('i16' | 'u16' | 'f32') - The audio data format. #### Response Example ```json { "sampleRate": 44100, "channels": 2, "format": "f32" } ``` ## GET /cpal/config/output ### Description Retrieves the default output configuration for a specified audio device. ### Method GET ### Endpoint `/cpal/config/output` ### Parameters #### Query Parameters - **deviceId** (string) - Required - The identifier of the audio device. ### Response #### Success Response (200) - **sampleRate** (number) - The sample rate of the audio stream. - **channels** (number) - The number of audio channels. - **format** ('i16' | 'u16' | 'f32') - The audio data format. #### Response Example ```json { "sampleRate": 48000, "channels": 2, "format": "f32" } ``` ``` -------------------------------- ### Create Audio Stream (JavaScript) Source: https://context7.com/saeta-eth/node-cpal/llms.txt Creates a new audio stream for either input (recording) or output (playback). For input streams, a callback function is invoked with audio data buffers. Configuration options include sample rate, channels, and format. ```javascript const cpal = require('node-cpal'); // Create an INPUT stream for recording const inputDevice = cpal.getDefaultInputDevice(); const inputConfig = cpal.getDefaultInputConfig(inputDevice.deviceId); const inputStream = cpal.createStream( inputDevice.deviceId, true, // true for input stream { sampleRate: inputConfig.sampleRate, channels: inputConfig.channels, sampleFormat: 'f32', }, (data) => { // Process incoming audio data console.log(`Received ${data.length} samples`); // data is a Float32Array containing audio samples const rms = Math.sqrt(data.reduce((sum, sample) => sum + sample * sample, 0) / data.length); console.log(`Audio level: ${(rms * 100).toFixed(1)}%`); } ); // Create an OUTPUT stream for playback const outputDevice = cpal.getDefaultOutputDevice(); const outputConfig = cpal.getDefaultOutputConfig(outputDevice.deviceId); const outputStream = cpal.createStream( outputDevice.deviceId, false, // false for output stream { sampleRate: outputConfig.sampleRate, channels: outputConfig.channels, sampleFormat: 'f32', }, () => {} // Empty callback for output streams ); ``` -------------------------------- ### createStream Source: https://context7.com/saeta-eth/node-cpal/llms.txt Creates an audio stream for either input (recording) or output (playback) with specified device, configuration, and a callback for data handling. ```APIDOC ## createStream ### Description Creates an audio stream for either input (recording) or output (playback). For input streams, a callback function receives audio data as Float32Array buffers. ### Method POST (Conceptual - this is a function call, not an HTTP endpoint) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **deviceId** (string) - The ID of the audio device to use. - **isInput** (boolean) - Set to `true` for an input stream (recording), `false` for an output stream (playback). - **config** (object) - An object containing stream configuration: - **sampleRate** (number) - The desired sample rate in Hz. - **channels** (number) - The desired number of audio channels. - **sampleFormat** (string) - The desired sample format (e.g., 'f32'). - **callback** (function) - A callback function. For input streams, it receives `data` (Float32Array). For output streams, it is typically empty. ### Request Example ```javascript const cpal = require('node-cpal'); // Create an INPUT stream for recording const inputDevice = cpal.getDefaultInputDevice(); const inputConfig = cpal.getDefaultInputConfig(inputDevice.deviceId); const inputStream = cpal.createStream( inputDevice.deviceId, true, // true for input stream { sampleRate: inputConfig.sampleRate, channels: inputConfig.channels, sampleFormat: 'f32', }, (data) => { // Process incoming audio data console.log(`Received ${data.length} samples`); // data is a Float32Array containing audio samples const rms = Math.sqrt(data.reduce((sum, sample) => sum + sample * sample, 0) / data.length); console.log(`Audio level: ${(rms * 100).toFixed(1)}%`); } ); // Create an OUTPUT stream for playback const outputDevice = cpal.getDefaultOutputDevice(); const outputConfig = cpal.getDefaultOutputConfig(outputDevice.deviceId); const outputStream = cpal.createStream( outputDevice.deviceId, false, // false for output stream { sampleRate: outputConfig.sampleRate, channels: outputConfig.channels, sampleFormat: 'f32', }, () => {} // Empty callback for output streams ); ``` ### Response #### Success Response (Object) - **stream** (object) - An object representing the created audio stream. #### Response Example ```javascript // For input stream: // { // "type": "input", // "deviceId": "default", // "sampleRate": 48000, // "channels": 1, // "sampleFormat": "f32" // } // For output stream: // { // "type": "output", // "deviceId": "default", // "sampleRate": 48000, // "channels": 2, // "sampleFormat": "f32" // } ``` ``` -------------------------------- ### getDefaultOutputConfig Source: https://context7.com/saeta-eth/node-cpal/llms.txt Retrieves the default output configuration for a specified audio device, including sample rate, channel count, and audio format. ```APIDOC ## getDefaultOutputConfig ### Description Returns the default output configuration for the specified device, providing ready-to-use stream configuration parameters. ### Method GET (Conceptual - this is a function call, not an HTTP endpoint) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript const cpal = require('node-cpal'); const outputDevice = cpal.getDefaultOutputDevice(); const config = cpal.getDefaultOutputConfig(outputDevice.deviceId); console.log(`Sample Rate: ${config.sampleRate} Hz`); console.log(`Channels: ${config.channels}`); console.log(`Format: ${config.sampleFormat}`); ``` ### Response #### Success Response (Object) - **sampleRate** (number) - The default sample rate in Hz. - **channels** (number) - The default number of audio channels. - **sampleFormat** (string) - The default sample format (e.g., 'f32'). #### Response Example ```json { "sampleRate": 48000, "channels": 2, "sampleFormat": "f32" } ``` ``` -------------------------------- ### getDefaultInputConfig Source: https://context7.com/saeta-eth/node-cpal/llms.txt Retrieves the default input configuration for a specified audio device, providing sample rate, channel count, and audio format. ```APIDOC ## getDefaultInputConfig ### Description Returns the default input configuration for the specified device, providing ready-to-use stream configuration parameters. ### Method GET (Conceptual - this is a function call, not an HTTP endpoint) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript const cpal = require('node-cpal'); const inputDevice = cpal.getDefaultInputDevice(); const config = cpal.getDefaultInputConfig(inputDevice.deviceId); console.log(`Sample Rate: ${config.sampleRate} Hz`); console.log(`Channels: ${config.channels}`); console.log(`Format: ${config.sampleFormat}`); ``` ### Response #### Success Response (Object) - **sampleRate** (number) - The default sample rate in Hz. - **channels** (number) - The default number of audio channels. - **sampleFormat** (string) - The default sample format (e.g., 'f32'). #### Response Example ```json { "sampleRate": 48000, "channels": 1, "sampleFormat": "f32" } ``` ``` -------------------------------- ### resumeStream Source: https://context7.com/saeta-eth/node-cpal/llms.txt Resumes a previously paused audio stream, continuing audio playback or recording from where it was interrupted. ```APIDOC ## resumeStream ### Description Resumes a previously paused audio stream, continuing audio playback or recording from where it was paused. ### Method POST (Conceptual - this is a function call, not an HTTP endpoint) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **stream** (object) - The audio stream object to resume. ### Request Example ```javascript const cpal = require('node-cpal'); const outputDevice = cpal.getDefaultOutputDevice(); const config = cpal.getDefaultOutputConfig(outputDevice.deviceId); const stream = cpal.createStream(outputDevice.deviceId, false, config, () => {}); // Pause the stream cpal.pauseStream(stream); console.log('Stream paused'); // Resume after some time setTimeout(() => { cpal.resumeStream(stream); console.log('Stream resumed'); }, 2000); ``` ### Response #### Success Response (void) This function does not return a value upon successful execution. #### Response Example N/A ``` -------------------------------- ### writeToStream Source: https://context7.com/saeta-eth/node-cpal/llms.txt Writes audio data, provided as a Float32Array, to an output audio stream for playback. ```APIDOC ## writeToStream ### Description Writes audio data to an output stream. The data must be a Float32Array containing audio samples. ### Method POST (Conceptual - this is a function call, not an HTTP endpoint) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **stream** (object) - The output audio stream object to write to. - **audioData** (Float32Array) - A Float32Array containing the audio samples to be written. ### Request Example ```javascript const cpal = require('node-cpal'); // Set up output stream const outputDevice = cpal.getDefaultOutputDevice(); const config = cpal.getDefaultOutputConfig(outputDevice.deviceId); const stream = cpal.createStream( outputDevice.deviceId, false, config, () => {} ); // Generate a 440 Hz sine wave (A4 note) const FREQUENCY = 440; const DURATION_SECONDS = 1; const sampleCount = config.sampleRate * config.channels * DURATION_SECONDS; const bufferSize = 1024; let sampleClock = 0; function generateSineWave(size) { const buffer = new Float32Array(size); for (let i = 0; i < size; i++) { buffer[i] = Math.sin((2 * Math.PI * FREQUENCY * sampleClock) / config.sampleRate); sampleClock++; } return buffer; } // Write audio in chunks async function playTone() { let samplesWritten = 0; while (samplesWritten < sampleCount) { const samplesToWrite = Math.min(bufferSize, sampleCount - samplesWritten); const audioData = generateSineWave(samplesToWrite); cpal.writeToStream(stream, audioData); samplesWritten += samplesToWrite; await new Promise((resolve) => setTimeout(resolve, 10)); } cpal.closeStream(stream); } playTone(); ``` ### Response #### Success Response (void) This function does not return a value upon successful execution. #### Response Example N/A ``` -------------------------------- ### Create Audio Stream (JavaScript) Source: https://github.com/saeta-eth/node-cpal/blob/main/README.md Creates an audio stream for either input or output. For input streams, a callback function processes incoming audio data. For output streams, data can be written to it. ```javascript // Creating an input stream const inputDevice = cpal.getDefaultInputDevice(); const inputConfig = cpal.getDefaultInputConfig(inputDevice); const inputStream = cpal.createStream( inputDevice, true, // true for input stream { sampleRate: inputConfig.sampleRate, channels: inputConfig.channels, format: 'f32', }, (data) => { // Process incoming audio data console.log(`Received ${data.length} samples`); } ); // Creating an output stream const outputDevice = cpal.getDefaultOutputDevice(); const outputConfig = cpal.getDefaultOutputConfig(outputDevice); const outputStream = cpal.createStream( outputDevice, false, // false for output stream { sampleRate: outputConfig.sampleRate, channels: outputConfig.channels, format: 'f32', }, () => {} // No callback needed for output ); ``` -------------------------------- ### TypeScript Type Definitions for node-cpal Source: https://context7.com/saeta-eth/node-cpal/llms.txt Provides TypeScript interfaces for essential node-cpal structures, including audio device configurations, stream configurations, audio device details, audio host information, and stream handles. These types aid in static analysis and type safety. ```typescript interface AudioDeviceConfig { minSampleRate: number; maxSampleRate: number; channels: number; sampleFormat: 'i16' | 'u16' | 'f32'; } interface StreamConfig { sampleRate: number; channels: number; sampleFormat: 'i16' | 'u16' | 'f32'; } interface AudioDevice { name: string; hostId: string; deviceId: string; isDefaultInput: boolean; isDefaultOutput: boolean; supportedInputConfigs?: AudioDeviceConfig[]; supportedOutputConfigs?: AudioDeviceConfig[]; } interface AudioHost { id: string; name: string; } interface StreamHandle { deviceId: string; streamId: string; } ``` -------------------------------- ### Stream Management API Source: https://github.com/saeta-eth/node-cpal/blob/main/README.md Functions for creating, managing, and controlling audio streams. ```APIDOC ## POST /cpal/stream/create ### Description Creates an audio stream. For input streams, a callback function is provided to process incoming audio data. ### Method POST ### Endpoint `/cpal/stream/create` ### Parameters #### Request Body - **deviceId** (string) - Required - The identifier of the audio device. - **isInput** (boolean) - Required - Set to `true` for an input stream, `false` for an output stream. - **config** (object) - Required - The stream configuration. - **sampleRate** (number) - Required - The desired sample rate. - **channels** (number) - Required - The number of audio channels. - **format** ('i16' | 'u16' | 'f32') - Required - The audio data format. - **callback** (function) - Optional - A callback function for input streams that receives `Float32Array` audio data. ### Request Example ```json { "deviceId": "default_input", "isInput": true, "config": { "sampleRate": 44100, "channels": 2, "format": "f32" } } ``` ### Response #### Success Response (200) - **streamHandle** (object) - An object representing the created stream. - **deviceId** (string) - The ID of the device associated with the stream. - **streamId** (string) - The unique identifier for the stream. #### Response Example ```json { "streamHandle": { "deviceId": "default_input", "streamId": "stream_123" } } ``` ## POST /cpal/stream/write ### Description Writes audio data to an active output stream. ### Method POST ### Endpoint `/cpal/stream/write` ### Parameters #### Request Body - **streamHandle** (object) - Required - The handle of the output stream to write to. - **deviceId** (string) - Required - The device ID from the stream handle. - **streamId** (string) - Required - The stream ID from the stream handle. - **data** (Float32Array) - Required - The audio data to write. ### Response #### Success Response (200) - **status** (string) - Indicates the success of the operation (e.g., "success"). #### Response Example ```json { "status": "success" } ``` ## POST /cpal/stream/pause ### Description Pauses an active audio stream. ### Method POST ### Endpoint `/cpal/stream/pause` ### Parameters #### Request Body - **streamHandle** (object) - Required - The handle of the stream to pause. - **deviceId** (string) - Required - The device ID from the stream handle. - **streamId** (string) - Required - The stream ID from the stream handle. ### Response #### Success Response (200) - **status** (string) - Indicates the success of the operation (e.g., "success"). #### Response Example ```json { "status": "success" } ``` ## POST /cpal/stream/resume ### Description Resumes a paused audio stream. ### Method POST ### Endpoint `/cpal/stream/resume` ### Parameters #### Request Body - **streamHandle** (object) - Required - The handle of the stream to resume. - **deviceId** (string) - Required - The device ID from the stream handle. - **streamId** (string) - Required - The stream ID from the stream handle. ### Response #### Success Response (200) - **status** (string) - Indicates the success of the operation (e.g., "success"). #### Response Example ```json { "status": "success" } ``` ## POST /cpal/stream/close ### Description Closes and cleans up an audio stream. ### Method POST ### Endpoint `/cpal/stream/close` ### Parameters #### Request Body - **streamHandle** (object) - Required - The handle of the stream to close. - **deviceId** (string) - Required - The device ID from the stream handle. - **streamId** (string) - Required - The stream ID from the stream handle. ### Response #### Success Response (200) - **status** (string) - Indicates the success of the operation (e.g., "success"). #### Response Example ```json { "status": "success" } ``` ## GET /cpal/stream/isActive ### Description Checks if an audio stream is currently active. ### Method GET ### Endpoint `/cpal/stream/isActive` ### Parameters #### Query Parameters - **streamHandle** (object) - Required - The handle of the stream to check. - **deviceId** (string) - Required - The device ID from the stream handle. - **streamId** (string) - Required - The stream ID from the stream handle. ### Response #### Success Response (200) - **isActive** (boolean) - `true` if the stream is active, `false` otherwise. #### Response Example ```json { "isActive": true } ``` ``` -------------------------------- ### Write to Audio Stream (JavaScript) Source: https://context7.com/saeta-eth/node-cpal/llms.txt Writes audio data, provided as a Float32Array, to an output audio stream. This function is used for audio playback, allowing raw audio samples to be sent to the sound device. ```javascript const cpal = require('node-cpal'); // Set up output stream const outputDevice = cpal.getDefaultOutputDevice(); const config = cpal.getDefaultOutputConfig(outputDevice.deviceId); const stream = cpal.createStream( outputDevice.deviceId, false, config, () => {} ); // Generate a 440 Hz sine wave (A4 note) const FREQUENCY = 440; const DURATION_SECONDS = 1; const sampleCount = config.sampleRate * config.channels * DURATION_SECONDS; const bufferSize = 1024; let sampleClock = 0; function generateSineWave(size) { const buffer = new Float32Array(size); for (let i = 0; i < size; i++) { buffer[i] = Math.sin((2 * Math.PI * FREQUENCY * sampleClock) / config.sampleRate); sampleClock++; } return buffer; } // Write audio in chunks async function playTone() { let samplesWritten = 0; while (samplesWritten < sampleCount) { const samplesToWrite = Math.min(bufferSize, sampleCount - samplesWritten); const audioData = generateSineWave(samplesToWrite); cpal.writeToStream(stream, audioData); samplesWritten += samplesToWrite; await new Promise((resolve) => setTimeout(resolve, 10)); } cpal.closeStream(stream); } playTone(); ``` -------------------------------- ### Type Definitions (TypeScript) Source: https://github.com/saeta-eth/node-cpal/blob/main/README.md Defines the TypeScript interfaces for audio device and stream configurations, as well as stream handles. ```typescript interface AudioDeviceConfig { minSampleRate: number; maxSampleRate: number; channels: number; format: 'i16' | 'u16' | 'f32'; } interface StreamConfig { sampleRate: number; channels: number; format: 'i16' | 'u16' | 'f32'; } interface StreamHandle { deviceId: string; streamId: string; } ``` -------------------------------- ### Resume Audio Stream (JavaScript) Source: https://github.com/saeta-eth/node-cpal/blob/main/README.md Resumes an audio stream that was previously paused. This will re-initiate audio processing or playback. ```javascript cpal.resumeStream(stream); ``` -------------------------------- ### Write to Output Stream (JavaScript) Source: https://github.com/saeta-eth/node-cpal/blob/main/README.md Writes a buffer of audio data to an active output audio stream. This function is essential for playing audio. ```javascript // Write a buffer of audio data to the stream cpal.writeToStream(outputStream, audioBuffer); ``` -------------------------------- ### pauseStream Source: https://context7.com/saeta-eth/node-cpal/llms.txt Pauses an active audio stream. The stream can be resumed later using the `resumeStream` function. ```APIDOC ## pauseStream ### Description Pauses an active audio stream. The stream can be resumed later with `resumeStream`. ### Method POST (Conceptual - this is a function call, not an HTTP endpoint) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **stream** (object) - The audio stream object to pause. ### Request Example ```javascript const cpal = require('node-cpal'); const outputDevice = cpal.getDefaultOutputDevice(); const config = cpal.getDefaultOutputConfig(outputDevice.deviceId); const stream = cpal.createStream(outputDevice.deviceId, false, config, () => {}); // ... write some audio data ... // Pause the stream cpal.pauseStream(stream); console.log('Stream paused'); // Check if stream is still active const isActive = cpal.isStreamActive(stream); console.log(`Stream active: ${isActive}`); ``` ### Response #### Success Response (void) This function does not return a value upon successful execution. #### Response Example N/A ``` -------------------------------- ### Check Audio Stream Activity in JavaScript Source: https://context7.com/saeta-eth/node-cpal/llms.txt Shows how to check if an audio stream is currently active using `cpal.isStreamActive`. This function returns a boolean indicating the stream's operational status, even after pausing or resuming. ```javascript const cpal = require('node-cpal'); const outputDevice = cpal.getDefaultOutputDevice(); const config = cpal.getDefaultOutputConfig(outputDevice.deviceId); const stream = cpal.createStream(outputDevice.deviceId, false, config, () => {}); console.log(`Stream active: ${cpal.isStreamActive(stream)}`); // true cpal.pauseStream(stream); console.log(`Stream active after pause: ${cpal.isStreamActive(stream)}`); // false cpal.resumeStream(stream); console.log(`Stream active after resume: ${cpal.isStreamActive(stream)}`); // true cpal.closeStream(stream); ``` -------------------------------- ### Pause Audio Stream (JavaScript) Source: https://context7.com/saeta-eth/node-cpal/llms.txt Pauses an active audio stream, suspending either playback or recording. The stream can later be resumed using the `resumeStream` function. ```javascript const cpal = require('node-cpal'); const outputDevice = cpal.getDefaultOutputDevice(); const config = cpal.getDefaultOutputConfig(outputDevice.deviceId); const stream = cpal.createStream(outputDevice.deviceId, false, config, () => {}); // ... write some audio data ... // Pause the stream cpal.pauseStream(stream); console.log('Stream paused'); // Check if stream is still active const isActive = cpal.isStreamActive(stream); console.log(`Stream active: ${isActive}`); ``` -------------------------------- ### Close Audio Stream (JavaScript) Source: https://github.com/saeta-eth/node-cpal/blob/main/README.md Closes an audio stream and releases associated resources. This should be called when the stream is no longer needed. ```javascript cpal.closeStream(stream); ``` -------------------------------- ### Check if Stream is Active (JavaScript) Source: https://github.com/saeta-eth/node-cpal/blob/main/README.md Checks the current status of an audio stream, returning true if it is active and false otherwise. ```javascript const isActive = cpal.isStreamActive(stream); console.log(`Stream is ${isActive ? 'active' : 'inactive'}`); ``` -------------------------------- ### Pause Audio Stream (JavaScript) Source: https://github.com/saeta-eth/node-cpal/blob/main/README.md Pauses an active audio stream. This will stop audio processing or playback until the stream is resumed. ```javascript cpal.pauseStream(stream); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.