naudiodon

repository·master·Indexed 43 days ago

https://github.com/streampunk/naudiodon

Node.js stream bindings for PortAudio version 2.4.0, providing cross-platform audio recording and playback. It exposes audio functionality through Readable, Writable, and Duplex streams, supporting asynchronous processing and back-pressure. Includes utilities to list available audio devices and host APIs, and provides the AudioIO interface for configuring sample rates, channel counts, and bit depths.

Tokens
3.7K
Snippets
11
Records
16
Agent score
56%

What's inside naudiodon

  1. Build PortAudio for Naudiodon on Windows

    master

    To use Naudiodon on Windows, you must manually build the PortAudio dependency using MSVC. Follow these steps:

    1. Prepare the build directory: Copy build.bat, portaudio.vcxproj, and portaudio.def into the portaudio\build\msvc directory.
    2. Execute the build: Run build.bat.
    3. Deploy the binaries: Copy the resulting portaudio_x64.dll and portaudio_x64.lib from portaudio\build\msvc\X64\Release into the naudiodon\portaudio\bin directory.
    # Step 1: Copy files to portaudio\build\msvc
    # Step 2: Run build
    build.bat
    # Step 3: Copy binaries to naudiodon\portaudio\bin
    copy portaudio\build\msvc\X64\Release\portaudio_x64.dll naudiodon\portaudio\bin\
    copy portaudio\build\msvc\X64\Release\portaudio_x64.lib naudiodon\portaudio\bin\
  2. Install naudiodon via npm

    master

    Install naudiodon using npm. Ensure that Node.js is installed and that node-gyp is available to build native modules. The package includes a local copy of the PortAudio library, so no separate PortAudio installation is required.

    Note for Raspberry Pi users: This library is not intended for use with the internal sound card. Use an external USB sound card or a GPIO breakout board (e.g., Pi-DAC+ Full-HD Audio Card).

    npm install naudiodon
  3. Troubleshoot MacOS Carbon Component Manager warnings

    master
    If you see a warning regarding the deprecated Carbon Component Manager for hosting Audio Units on MacOS, note that this is a known issue with the underlying PortAudio library. The latest version of naudiodon includes a locally compiled version of PortAudio that uses more up-to-date Apple APIs to mitigate this.
  4. List host audio APIs

    master

    Use the getHostAPIs() function to retrieve the available host audio APIs. The returned object contains a defaultHostAPI index and a HostAPIs array. Each API entry includes id, name, deviceCount, defaultInput, and defaultOutput. The defaultInput and defaultOutput values can be used to identify default devices for playback or recording.

    var portAudio = require('naudiodon');
    
    console.log(portAudio.getHostAPIs());
  5. Play audio using AudioIO Writable Streams

    master

    To play audio, create an instance of AudioIO providing an outOptions object. This instance acts as a Node.js Writable Stream.

    Configuration options for outOptions:

    • channelCount: Number of audio channels.
    • sampleFormat: The bit depth (e.g., portAudio.SampleFormat16Bit).
    • sampleRate: The sample rate (e.g., 48000).
    • deviceId: The device ID to use. Use -1 or omit to use the default device.
    • closeOnError: If true, the stream closes when an audio error is detected; if false, it just logs the error.
    const fs = require('fs');
    const portAudio = require('naudiodon');
    
    // Create an instance of AudioIO with outOptions, which returns a WritableStream
    var ao = new portAudio.AudioIO({
      outOptions: {
        channelCount: 2,
        sampleFormat: portAudio.SampleFormat16Bit,
        sampleRate: 48000,
        deviceId: -1, // Use -1 or omit the deviceId to select the default device
        closeOnError: true
      }
    });
    
    // Create a stream to pipe into the AudioOutput
    var rs = fs.createReadStream('steam_48000.wav');
    
    // Start piping data and start streaming
    rs.pipe(ao);
    ao.start();
  6. List available audio devices

    master

    Use the getDevices() function to retrieve an array of supported audio devices. Each device object contains information such as id, name, maxInputChannels, maxOutputChannels, defaultSampleRate, and hostAPIName. The id can be used to specify a particular device when configuring AudioIO via the deviceId option.

    var portAudio = require('naudiodon');
    
    console.log(portAudio.getDevices());
  7. Perform bi-directional audio with AudioIO Duplex Streams

    master

    To create a bi-directional audio stream, create an instance of AudioIO providing both inOptions and outOptions. This instance acts as a Node.js Duplex Stream.

    Configuration options: Both inOptions and outOptions support channelCount, sampleFormat, sampleRate, and deviceId.

    var portAudio = require('naudiodon');
    
    // Create an instance of AudioIO with inOptions and outOptions, which will return a DuplexStream
    var aio = new portAudio.AudioIO({
      inOptions: {
        channelCount: 2,
        sampleFormat: portAudio.SampleFormat16Bit,
        sampleRate: 44100,
        deviceId: -1
      },
      outOptions: {
        channelCount: 2,
        sampleFormat: portAudio.SampleFormat16Bit,
        sampleRate: 44100,
        deviceId: -1
      }
    });
    
    aio.start();
  8. Record audio using AudioIO Readable Streams

    master

    To record audio, create an instance of AudioIO providing an inOptions object. This instance acts as a Node.js Readable Stream.

    Configuration options for inOptions:

    • channelCount: Number of audio channels.
    • sampleFormat: The bit depth (e.g., portAudio.SampleFormat16Bit).
    • sampleRate: The sample rate.
    • deviceId: The device ID to use. Use -1 or omit to use the default device.
    • closeOnError: If true, the stream closes when an audio error is detected; if false, it just logs the error.

    Important Notes:

    • Recording produces raw audio data. You must manually add headers (like WAV) if you want to create standard audio files.
    • Each buffer emitted by the stream contains a timestamp property representing the time value for the first sample in that buffer.
    • Call ai.quit() to stop the recording gracefully.
    var fs = require('fs');
    var portAudio = require('naudiodon');
    
    // Create an instance of AudioIO with inOptions, which returns a ReadableStream
    var ai = new portAudio.AudioIO({
      inOptions: {
        channelCount: 2,
        sampleFormat: portAudio.SampleFormat16Bit,
        sampleRate: 44100,
        deviceId: -1,
        closeOnError: true
      }
    });
    
    // Create a write stream to write out to a raw audio file
    var ws = fs.createWriteStream('rawAudio.raw');
    
    // Accessing the timestamp on data buffers
    ai.on('data', buf => console.log(buf.timestamp));
    
    // Start streaming
    ai.pipe(ws);
    ai.start();
    
    // Stopping the recording
    process.on('SIGINT', () => {
      console.log('Received SIGINT. Stopping recording.');
      ai.quit();
    });
  9. Configure audio settings via AudioOptions

    master

    When using naudiodon, audio behavior is controlled by an options object. The underlying C++ implementation uses the following keys to configure audio streams. If a key is omitted, the specified default value is used.

    KeyTypeDefaultDescription
    deviceIdNumber0xffffffffThe ID of the audio device. 0xffffffff represents the default device.
    sampleRateNumber44100The audio sample rate in Hz.
    channelCountNumber2The number of audio channels (e.g., 1 for mono, 2 for stereo).
    sampleFormatNumber8The internal representation of the sample format.
    sampleBitsNumber(Derived)If sampleFormat is 1, sampleBits is 32; otherwise, it matches sampleFormat.
    maxQueueNumber2The maximum number of frames/buffers in the queue.
    framesPerBufferNumber0The number of frames per buffer.
    closeOnErrorBooleantrueWhether the stream should automatically close if an error occurs.
  10. Create audio streams with AudioIO

    master

    The AudioIO function is the primary way to interact with audio hardware. It returns a Node.js stream (Readable, Writable, or Duplex) depending on the options provided.

    Stream Types

    • Duplex Stream: Created if both inOptions and outOptions are provided. Used for bi-directional audio.
    • Readable Stream: Created if only inOptions is provided. Used for recording audio.
    • Writable Stream: Created if only outOptions is provided. Used for playing audio.

    Stream Control Methods

    • ioStream.start(): Starts the audio I/O.
    • ioStream.quit(callback): Gracefully stops the audio I/O using the 'WAIT' flag. If a callback is provided, it is executed after quitting.
    • ioStream.abort(callback): Immediately stops the audio I/O using the 'ABORT' flag. If a callback is provided, it is executed after aborting.

    Configuration Options

    Both inOptions and outOptions can include a highwaterMark property to control the internal buffer size (defaults to 16384).

    const { AudioIO, SampleFormatFloat32 } = require('naudiodon');
    
    // Example: Creating a Duplex stream for bi-directional audio
    const io = AudioIO({
      inOptions: {
        device: 1, // device index
        format: SampleFormatFloat32,
        channels: 2,
        sampleRate: 44100,
        highwaterMark: 16384
      },
      outOptions: {
        device: 1,
        format: SampleFormatFloat32,
        channels: 2,
        sampleRate: 44100,
        highwaterMark: 16384
      }
    });
    
    io.start();
    
    // Handle stream lifecycle
    io.on('finish', () => console.log('Stream finished'));
    io.on('error', (err) => console.error('AudioIO Error:', err));
    
    // To stop gracefully:
    // await io.quit();