### RtAudio Installation with vcpkg (Shell) Source: https://github.com/thestk/rtaudio/blob/master/README.md This shows how to install RtAudio using the vcpkg package manager. It first bootstraps vcpkg if necessary, integrates it with the system, and then installs the rtaudio package. ```bash ./bootstrap-vcpkg.sh ./vcpkg integrate install ./vcpkg install rtaudio ``` -------------------------------- ### Record Audio Input with RtAudio C++ Source: https://github.com/thestk/rtaudio/blob/master/doc/doxygen/recording.txt This snippet demonstrates recording audio using RtAudio. It configures the audio stream for input, specifies the number of channels and sample rate, and defines a callback function (`record`) that receives the input audio data. The example includes device selection, stream opening, starting, stopping, and closing. ```cpp #include "RtAudio.h" #include #include #include int record( void *outputBuffer, void *inputBuffer, unsigned int nBufferFrames, double streamTime, RtAudioStreamStatus status, void *userData ) { if ( status ) std::cout << "Stream overflow detected!" << std::endl; // Do something with the data in the "inputBuffer" buffer. return 0; } int main() { RtAudio adc; std::vector deviceIds = adc.getDeviceIds(); if ( deviceIds.size() < 1 ) { std::cout << "\nNo audio devices found!\n"; exit( 0 ); } RtAudio::StreamParameters parameters; parameters.deviceId = adc.getDefaultInputDevice(); parameters.nChannels = 2; parameters.firstChannel = 0; unsigned int sampleRate = 44100; unsigned int bufferFrames = 256; // 256 sample frames if ( adc.openStream( NULL, ¶meters, RTAUDIO_SINT16, sampleRate, &bufferFrames, &record ) ) { std::cout << '\n' << adc.getErrorText() << '\n' << std::endl; exit( 0 ); // problem with device settings } // Stream is open ... now start it. if ( adc.startStream() ) { std::cout << adc.getErrorText() << std::endl; goto cleanup; } char input; std::cout << "\nRecording ... press to quit.\n"; std::cin.get( input ); // Block released ... stop the stream if ( adc.isStreamRunning() ) adc.stopStream(); // or could call adc.abortStream(); cleanup: if ( adc.isStreamOpen() ) adc.closeStream(); return 0; } ``` -------------------------------- ### Configure API Documentation Installation Source: https://github.com/thestk/rtaudio/blob/master/meson_options.txt Control whether the generated API documentation is installed. This is a boolean option, typically set to false by default. ```text option('install_docs', type : 'boolean', value : 'false', description: 'Install API documentation') ``` -------------------------------- ### RtAudio Installation Rules Source: https://github.com/thestk/rtaudio/blob/master/CMakeLists.txt Defines the installation rules for the RtAudio library, including the library files, export targets, and header files, specifying their destinations in the installation directory. ```cmake install(TARGETS ${LIB_TARGETS} EXPORT RtAudioTargets LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} INCLUDES DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/rtaudio) install(FILES RtAudio.h rtaudio_c.h DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/rtaudio) ``` -------------------------------- ### Vcpkg Usage for RtAudio Source: https://github.com/thestk/rtaudio/blob/master/install.txt RtAudio can be built and installed using the vcpkg dependency manager. This process involves cloning the vcpkg repository, bootstrapping it, integrating it with your system, and then installing the 'rtaudio' package. The vcpkg port for RtAudio is maintained by the Microsoft team and community contributors. ```shell # Clone the vcpkg repository git clone https://github.com/Microsoft/vcpkg.git cd vcpkg # Bootstrap vcpkg (use .bat for Windows) ./bootstrap-vcpkg.sh # Integrate vcpkg with your system ./vcpkg integrate install # Install rtaudio ./vcpkg install rtaudio ``` -------------------------------- ### Compile RtAudio for Linux with ALSA API Source: https://github.com/thestk/rtaudio/blob/master/doc/doxygen/compiling.txt This command compiles the 'audioprobe' example for Linux using the ALSA audio API. It requires the 'asound' and 'pthread' libraries and defines the '__LINUX_ALSA__' preprocessor macro. ```bash g++ -Wall -D__LINUX_ALSA__ -o audioprobe audioprobe.cpp RtAudio.cpp -lasound -lpthread ``` -------------------------------- ### Compile RtAudio for macOS with CoreAudio API Source: https://github.com/thestk/rtaudio/blob/master/doc/doxygen/compiling.txt This command compiles the 'audioprobe' example for macOS using the CoreAudio API. It requires 'pthread', CoreAudio, and CoreFoundation frameworks and defines the '__MACOSX_CORE__' preprocessor macro. ```bash g++ -Wall -D__MACOSX_CORE__ -o audioprobe audioprobe.cpp RtAudio.cpp -framework CoreAudio -framework CoreFoundation -lpthread ``` -------------------------------- ### RtAudio Include Directories Setup Source: https://github.com/thestk/rtaudio/blob/master/CMakeLists.txt Configures the include directories for the RtAudio target, making the current source directory and the install include directory publicly available, while private headers are also included. ```cmake target_include_directories(rtaudio PUBLIC $ $ PRIVATE ${INCDIRS}) ``` -------------------------------- ### Initialize RtAudio and Query Devices Source: https://context7.com/thestk/rtaudio/llms.txt Initializes the RtAudio system and enumerates available audio devices. It demonstrates how to set up an error callback, get the current API, and retrieve detailed information for each audio device, including its name, ID, channel counts, default status, supported sample rates, and native audio formats. ```cpp #include "RtAudio.h" #include void errorCallback(RtAudioErrorType type, const std::string &errorText) { std::cerr << "RtAudio Error: " << errorText << std::endl; } int main() { // Create RtAudio instance with error callback RtAudio audio(RtAudio::UNSPECIFIED, &errorCallback); // Get current API std::cout << "Using API: " << RtAudio::getApiDisplayName(audio.getCurrentApi()) << std::endl; // Get device count unsigned int deviceCount = audio.getDeviceCount(); std::cout << "Found " << deviceCount << " devices" << std::endl; // Get device IDs std::vector deviceIds = audio.getDeviceIds(); // Get device information for (unsigned int id : deviceIds) { RtAudio::DeviceInfo info = audio.getDeviceInfo(id); std::cout << "\nDevice: " << info.name << std::endl; std::cout << " ID: " << info.ID << std::endl; std::cout << " Output channels: " << info.outputChannels << std::endl; std::cout << " Input channels: " << info.inputChannels << std::endl; std::cout << " Duplex channels: " << info.duplexChannels << std::endl; std::cout << " Default output: " << (info.isDefaultOutput ? "Yes" : "No") << std::endl; std::cout << " Default input: " << (info.isDefaultInput ? "Yes" : "No") << std::endl; std::cout << " Preferred sample rate: " << info.preferredSampleRate << " Hz" << std::endl; // Check supported formats if (info.nativeFormats & RTAUDIO_SINT16) std::cout << " Supports 16-bit int" << std::endl; if (info.nativeFormats & RTAUDIO_FLOAT32) std::cout << " Supports 32-bit float" << std::endl; // Display sample rates std::cout << " Sample rates: "; for (unsigned int rate : info.sampleRates) { std::cout << rate << " "; } std::cout << std::endl; } return 0; } ``` -------------------------------- ### Probe Audio Device Capabilities with C++ Source: https://github.com/thestk/rtaudio/blob/master/doc/doxygen/probe.txt This C++ example demonstrates how to query available audio devices, retrieve their IDs, and then scan through each device to print its name and maximum output channels. It utilizes the RtAudio library to interact with the audio system. ```cpp #include #include "RtAudio.h" int main() { RtAudio audio; // Get the list of device IDs std::vector< unsigned int > ids = audio.getDeviceIds(); if ( ids.size() == 0 ) { std::cout << "No devices found." << std::endl; return 0; } // Scan through devices for various capabilities RtAudio::DeviceInfo info; for ( unsigned int n=0; n #include #include // Pass-through function. int inout( void *outputBuffer, void *inputBuffer, unsigned int nBufferFrames, double streamTime, RtAudioStreamStatus status, void *data ) { // Since the number of input and output channels is equal, we can do // a simple buffer copy operation here. if ( status ) std::cout << "Stream over/underflow detected." << std::endl; unsigned int *bytes = (unsigned int *) data; memcpy( outputBuffer, inputBuffer, *bytes ); return 0; } int main() { RtAudio adac; std::vector deviceIds = adac.getDeviceIds(); if ( deviceIds.size() < 1 ) { std::cout << "\nNo audio devices found!\n"; exit( 0 ); } // Set the same number of channels for both input and output. unsigned int bufferBytes, bufferFrames = 512; RtAudio::StreamParameters iParams, oParams; iParams.deviceId = deviceIds[0]; // first available device iParams.nChannels = 2; oParams.deviceId = deviceIds[0]; // first available device oParams.nChannels = 2; if ( adac.openStream( &oParams, &iParams, RTAUDIO_SINT32, 44100, &bufferFrames, &inout, (void *)&bufferBytes ) ) { std::cout << '\n' << adac.getErrorText() << '\n' << std::endl; exit( 0 ); // problem with device settings } bufferBytes = bufferFrames * 2 * 4; if ( adac.startStream() ) { std::cout << adac.getErrorText() << std::endl; goto cleanup; } char input; std::cout << "\nRunning ... press to quit.\n"; std::cin.get(input); // Block released ... stop the stream if ( adac.isStreamRunning() ) adac.stopStream(); // or could call adac.abortStream(); cleanup: if ( adac.isStreamOpen() ) adac.closeStream(); return 0; } ``` -------------------------------- ### Compile RtAudio for Windows with DirectSound API (MinGW) Source: https://github.com/thestk/rtaudio/blob/master/doc/doxygen/compiling.txt This MinGW command compiles the 'audioprobe' example for Windows using the DirectSound API. It requires 'ole32', 'winmm', and 'dsound' libraries and defines the '__WINDOWS_DS__' preprocessor macro. ```bash g++ -Wall -D__WINDOWS_DS__ -o audioprobe audioprobe.cpp RtAudio.cpp -lole32 -lwinmm -ldsound ``` -------------------------------- ### Configure RtAudio on Unix-like Systems Source: https://github.com/thestk/rtaudio/blob/master/install.txt This section details how to configure and compile the RtAudio library on Unix-like systems. It involves unpacking the distribution, running the 'configure' script with various options to enable specific audio APIs, and then using 'make' to build the libraries and examples. Options like '--enable-debug', '--with-alsa', '--with-pulse', '--with-oss', '--with-jack', '--with-core', '--with-asio', '--with-wasapi', and '--with-ds' allow customization of API support. The CXX variable can be used to specify a different compiler. ```shell # Unpack the RtAudio distribution tar -xzf rtaudio-x.x.tar.gz # Navigate to the directory cd rtaudio-x.x # Configure with default options ./configure # Configure with specific API support (e.g., ALSA and JACK on Linux) ./configure --with-alsa --with-jack # Configure with debugging enabled ./configure --enable-debug # Specify a different C++ compiler (e.g., CC) ./configure CXX=CC # Compile static and shared libraries, and examples make ``` -------------------------------- ### Configure RtAudio CMake Installation Paths Source: https://github.com/thestk/rtaudio/blob/master/CMakeLists.txt Sets the installation directory for CMake configuration files, specifically for the RtAudio project. This ensures that CMake can locate and use the installed RtAudio configuration during package discovery. ```cmake set(RTAUDIO_CMAKE_DESTINATION share/rtaudio) ``` -------------------------------- ### CMake Usage for RtAudio Source: https://github.com/thestk/rtaudio/blob/master/install.txt RtAudio provides CMake support for building the library. This involves creating a build directory, navigating into it, and then running CMake with the path to the 'CMakeLists.txt' file and any desired options. For example, to enable WASAPI support on Windows, you would use '-DRTAUDIO_WINDOWS_WASAPI=ON'. ```shell # Create a build directory mkdir _build_ cd _build_ # Configure using CMake, specifying the path to CMakeLists.txt and options # Example: Enable WASAPI support on Windows cmake .. -DRTAUDIO_WINDOWS_WASAPI=ON # Build the project (after CMake configuration is complete) # make (or equivalent for your build system) ``` -------------------------------- ### CMake Project Setup and C++ Standard Source: https://github.com/thestk/rtaudio/blob/master/CMakeLists.txt Initializes the CMake build system, sets the minimum required CMake version to 3.13, and defines the project name as 'RtAudio' with CXX language support. It also enforces C++11 standard compliance. ```cmake cmake_minimum_required(VERSION 3.13 FATAL_ERROR) project(RtAudio LANGUAGES CXX) set(CMAKE_CXX_STANDARD 11) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_EXTENSIONS OFF) ``` -------------------------------- ### Audio Playback with RtAudio C++ Source: https://github.com/thestk/rtaudio/blob/master/doc/doxygen/playback.txt This snippet demonstrates real-time audio playback using the RtAudio library in C++. It configures the audio stream, generates a sawtooth waveform using a callback function, and manages the stream's lifecycle. Dependencies include RtAudio and standard C++ libraries. ```cpp #include "RtAudio.h" #include #include // Two-channel sawtooth wave generator. int saw( void *outputBuffer, void *inputBuffer, unsigned int nBufferFrames, double streamTime, RtAudioStreamStatus status, void *userData ) { unsigned int i, j; double *buffer = (double *) outputBuffer; double *lastValues = (double *) userData; if ( status ) std::cout << "Stream underflow detected!" << std::endl; // Write interleaved audio data. for ( i=0; i= 1.0 ) lastValues[j] -= 2.0; } } return 0; } int main() { RtAudio dac; std::vector deviceIds = dac.getDeviceIds(); if ( deviceIds.size() < 1 ) { std::cout << "\nNo audio devices found!\n"; exit( 0 ); } RtAudio::StreamParameters parameters; parameters.deviceId = dac.getDefaultOutputDevice(); parameters.nChannels = 2; parameters.firstChannel = 0; unsigned int sampleRate = 44100; unsigned int bufferFrames = 256; // 256 sample frames double data[2] = {0, 0}; if ( dac.openStream( ¶meters, NULL, RTAUDIO_FLOAT64, sampleRate, &bufferFrames, &saw, (void *)&data ) ) { std::cout << '\'' << dac.getErrorText() << '\' << std::endl; exit( 0 ); // problem with device settings } // Stream is open ... now start it. if ( dac.startStream() ) { std::cout << dac.getErrorText() << std::endl; goto cleanup; } char input; std::cout << "\nPlaying ... press to quit.\n"; std::cin.get( input ); // Block released ... stop the stream if ( dac.isStreamRunning() ) dac.stopStream(); // or could call dac.abortStream(); cleanup: if ( dac.isStreamOpen() ) dac.closeStream(); return 0; } ``` -------------------------------- ### Configure and Install RtAudio CMake Package Configuration Source: https://github.com/thestk/rtaudio/blob/master/CMakeLists.txt Uses CMake's built-in functions to configure the RtAudioConfig.cmake file from its template and install it to the specified destination. It also generates a version file for package compatibility checks. ```cmake include(CMakePackageConfigHelpers) configure_package_config_file( ${CMAKE_CURRENT_BINARY_DIR}/RtAudioConfig.cmake.in ${CMAKE_CURRENT_BINARY_DIR}/RtAudioConfig.cmake INSTALL_DESTINATION ${RTAUDIO_CMAKE_DESTINATION} ) write_basic_package_version_file( ${CMAKE_CURRENT_BINARY_DIR}/RtAudioConfig-version.cmake VERSION ${FULL_VER} COMPATIBILITY AnyNewerVersion ) install( FILES ${CMAKE_CURRENT_BINARY_DIR}/RtAudioConfig.cmake ${CMAKE_CURRENT_BINARY_DIR}/RtAudioConfig-version.cmake DESTINATION ${RTAUDIO_CMAKE_DESTINATION} ) ``` -------------------------------- ### Open and Start Audio Output Stream in C++ with RtAudio Source: https://context7.com/thestk/rtaudio/llms.txt This C++ snippet initializes RtAudio, configures an output stream with stereo channels, a sample rate of 48000 Hz, and a buffer size of 512 frames. It uses a callback function to generate a 440 Hz sine wave and plays it for 3 seconds before stopping and closing the stream. Error handling is included for device discovery and stream operations. ```cpp #include "RtAudio.h" #include #include #include // Audio callback function - generates a sine wave int audioCallback(void *outputBuffer, void *inputBuffer, unsigned int nBufferFrames, double streamTime, RtAudioStreamStatus status, void *userData) { // Cast output buffer to the correct type float *buffer = (float *)outputBuffer; double *phase = (double *)userData; // Check for buffer underflow if (status == RTAUDIO_OUTPUT_UNDERFLOW) std::cout << "Stream underflow detected at time " << streamTime << std::endl; // Generate sine wave at 440 Hz const double frequency = 440.0; const double sampleRate = 48000.0; const double phaseIncrement = 2.0 * M_PI * frequency / sampleRate; for (unsigned int i = 0; i < nBufferFrames; i++) { float sample = 0.5f * sin(*phase); // Stereo output - write to both channels *buffer++ = sample; // left *buffer++ = sample; // right *phase += phaseIncrement; if (*phase >= 2.0 * M_PI) *phase -= 2.0 * M_PI; } // Return 0 to continue, 1 to stop and drain, 2 to abort immediately return 0; } int main() { RtAudio audio; if (audio.getDeviceCount() < 1) { std::cerr << "No audio devices found!" << std::endl; return 1; } // Configure output parameters RtAudio::StreamParameters outputParams; outputParams.deviceId = audio.getDefaultOutputDevice(); outputParams.nChannels = 2; // stereo outputParams.firstChannel = 0; // Stream configuration unsigned int sampleRate = 48000; unsigned int bufferFrames = 512; RtAudioFormat format = RTAUDIO_FLOAT32; // Stream options RtAudio::StreamOptions options; options.flags = RTAUDIO_MINIMIZE_LATENCY; options.numberOfBuffers = 2; options.streamName = "RtAudio Sine Wave"; // User data for callback double phase = 0.0; // Open the stream RtAudioErrorType error = audio.openStream(&outputParams, nullptr, format, sampleRate, &bufferFrames, &audioCallback, (void *)&phase, &options); if (error != RTAUDIO_NO_ERROR) { std::cerr << "Error opening stream: " << audio.getErrorText() << std::endl; return 1; } std::cout << "Stream opened with buffer size: " << bufferFrames << " frames" << std::endl; std::cout << "Latency: " << audio.getStreamLatency() << " frames" << std::endl; // Start the stream error = audio.startStream(); if (error != RTAUDIO_NO_ERROR) { std::cerr << "Error starting stream: " << audio.getErrorText() << std::endl; audio.closeStream(); return 1; } std::cout << "Playing 440 Hz sine wave for 3 seconds..." << std::endl; // Let it play for 3 seconds #ifdef WIN32 Sleep(3000); #else usleep(3000000); #endif // Stop the stream if (audio.isStreamRunning()) { error = audio.stopStream(); if (error != RTAUDIO_NO_ERROR) std::cerr << "Error stopping stream: " << audio.getErrorText() << std::endl; } // Close the stream if (audio.isStreamOpen()) audio.closeStream(); std::cout << "Done!" << std::endl; return 0; } ``` -------------------------------- ### C++ RtAudio: Record Audio Input Stream Source: https://context7.com/thestk/rtaudio/llms.txt This snippet shows how to configure and open an audio input stream using RtAudio in C++. It sets up the audio parameters such as device ID, number of channels, sample rate, and buffer size. A callback function `recordCallback` is defined to handle incoming audio data and store it in a buffer. The code also includes error handling for opening and starting the stream, and it stops recording after a specified duration. ```cpp #include "RtAudio.h" #include #include #include // Structure to hold recording data struct RecordData { std::vector buffer; unsigned int frameIndex; unsigned int totalFrames; }; // Audio input callback int recordCallback(void *outputBuffer, void *inputBuffer, unsigned int nBufferFrames, double streamTime, RtAudioStreamStatus status, void *userData) { RecordData *data = (RecordData *)userData; float *input = (float *)inputBuffer; if (status == RTAUDIO_INPUT_OVERFLOW) std::cout << "Stream overflow detected!" << std::endl; // Copy input to our buffer (assuming 2 channels) unsigned int channels = 2; for (unsigned int i = 0; i < nBufferFrames * channels; i++) { if (data->frameIndex < data->totalFrames) { data->buffer[data->frameIndex++] = input[i]; } } // Stop when buffer is full if (data->frameIndex >= data->totalFrames) return 1; // Stop and drain return 0; } int main() { RtAudio audio; if (audio.getDeviceCount() < 1) { std::cerr << "No audio devices found!" << std::endl; return 1; } // Configure input parameters RtAudio::StreamParameters inputParams; inputParams.deviceId = audio.getDefaultInputDevice(); inputParams.nChannels = 2; // stereo input inputParams.firstChannel = 0; unsigned int sampleRate = 44100; unsigned int bufferFrames = 256; unsigned int recordSeconds = 5; // Prepare recording buffer RecordData recordData; recordData.totalFrames = sampleRate * recordSeconds * 2; // 2 channels recordData.frameIndex = 0; recordData.buffer.resize(recordData.totalFrames); // Open input stream RtAudioErrorType error = audio.openStream(nullptr, &inputParams, RTAUDIO_FLOAT32, sampleRate, &bufferFrames, &recordCallback, &recordData); if (error != RTAUDIO_NO_ERROR) { std::cerr << "Error: " << audio.getErrorText() << std::endl; return 1; } std::cout << "Recording for " << recordSeconds << " seconds..." << std::endl; // Start recording error = audio.startStream(); if (error != RTAUDIO_NO_ERROR) { std::cerr << "Error: " << audio.getErrorText() << std::endl; audio.closeStream(); return 1; } // Wait for recording to complete while (audio.isStreamRunning()) { #ifdef WIN32 Sleep(100); #else usleep(100000); #endif } // Stop and close if (audio.isStreamOpen()) audio.closeStream(); // Calculate and display audio level float maxLevel = 0.0f; for (float sample : recordData.buffer) { float absLevel = std::abs(sample); if (absLevel > maxLevel) maxLevel = absLevel; } std::cout << "Recording complete!" << std::endl; std::cout << "Captured " << recordData.frameIndex << " samples" << std::endl; std::cout << "Peak level: " << maxLevel << std::endl; return 0; } ``` -------------------------------- ### Process Audio with Non-Interleaved Buffers in C++ Source: https://context7.com/thestk/rtaudio/llms.txt This C++ code demonstrates how to configure and use RtAudio with non-interleaved audio buffers. It defines a callback function that processes each audio channel separately and sets up the RtAudio stream with the RTAUDIO_NONINTERLEAVED flag. The example plays a stereo sine wave for 2 seconds. ```cpp #include "RtAudio.h" #include #include // Callback for non-interleaved buffers int nonInterleavedCallback(void *outputBuffer, void *inputBuffer, unsigned int nBufferFrames, double streamTime, RtAudioStreamStatus status, void *userData) { float *buffer = (float *)outputBuffer; double *phases = (double *)userData; // In non-interleaved mode, channels are stored sequentially // First all samples for channel 0, then all samples for channel 1, etc. const unsigned int channels = 2; const double frequency = 440.0; const double sampleRate = 48000.0; const double phaseIncrement = 2.0 * M_PI * frequency / sampleRate; // Process each channel separately for (unsigned int ch = 0; ch < channels; ch++) { float *channelBuffer = buffer + (ch * nBufferFrames); for (unsigned int i = 0; i < nBufferFrames; i++) { // Different phase for each channel to create stereo effect channelBuffer[i] = 0.5f * sin(phases[ch]); phases[ch] += phaseIncrement * (1.0 + ch * 0.01); if (phases[ch] >= 2.0 * M_PI) phases[ch] -= 2.0 * M_PI; } } return 0; } int main() { RtAudio audio; RtAudio::StreamParameters outputParams; outputParams.deviceId = audio.getDefaultOutputDevice(); outputParams.nChannels = 2; outputParams.firstChannel = 0; unsigned int sampleRate = 48000; unsigned int bufferFrames = 512; // Enable non-interleaved flag RtAudio::StreamOptions options; options.flags = RTAUDIO_NONINTERLEAVED; double phases[2] = {0.0, 0.0}; RtAudioErrorType error = audio.openStream(&outputParams, nullptr, RTAUDIO_FLOAT32, sampleRate, &bufferFrames, &nonInterleavedCallback, phases, &options); if (error != RTAUDIO_NO_ERROR) { std::cerr << "Error: " << audio.getErrorText() << std::endl; return 1; } std::cout << "Playing with non-interleaved buffers..." << std::endl; audio.startStream(); #ifdef WIN32 Sleep(2000); #else usleep(2000000); #endif audio.stopStream(); audio.closeStream(); return 0; } ``` -------------------------------- ### Get Compiled RtAudio APIs Source: https://context7.com/thestk/rtaudio/llms.txt Queries the RtAudio library to determine which audio APIs are available in the compiled version. It returns a list of supported APIs and allows searching for a specific API by name. This is useful for understanding the library's capabilities on the current system. ```cpp #include "RtAudio.h" #include #include int main() { // Get list of compiled audio APIs std::vector apis; RtAudio::getCompiledApi(apis); std::cout << "Available APIs:" << std::endl; for (size_t i = 0; i < apis.size(); i++) { std::cout << " " << RtAudio::getApiName(apis[i]) << " - " << RtAudio::getApiDisplayName(apis[i]) << std::endl; } // Get API by name RtAudio::Api selectedApi = RtAudio::getCompiledApiByName("alsa"); if (selectedApi != RtAudio::UNSPECIFIED) { std::cout << "Found ALSA API" << std::endl; } return 0; } ``` -------------------------------- ### Basic RtAudio Stream Callback (C++) Source: https://github.com/thestk/rtaudio/blob/master/README.md This example illustrates a basic RtAudio stream callback function in C++. The callback is invoked by RtAudio to process incoming audio data (input) and provide outgoing audio data (output). The function signature includes pointers to the audio buffers and the number of frames to process. ```c++ RtAudioCallbackInfo callbackInfo; // Example callback function signature static int audioCallback(void *outputBuffer, void *inputBuffer, int nFrames, double streamTime, RtAudioStreamStatus status, void *userData) { // Process inputBuffer and fill outputBuffer here // nFrames indicates the number of frames to process // userData can be used to pass custom data to the callback // Return 0 for success, non-zero for an error return 0; } ``` -------------------------------- ### C++ RtAudio Duplex Stream for Input/Output Passthrough Source: https://context7.com/thestk/rtaudio/llms.txt This C++ code snippet utilizes the RtAudio library to establish a full-duplex audio stream. It configures default input and output devices, sets sample rate and buffer size for low latency, and uses a callback function to copy incoming audio directly to the output buffer. Error handling for stream opening and starting is included, along with user interaction to stop the stream. ```cpp #include "RtAudio.h" #include #include // Duplex callback - simply passes input to output int duplexCallback(void *outputBuffer, void *inputBuffer, unsigned int nBufferFrames, double streamTime, RtAudioStreamStatus status, void *userData) { if (status) { if (status == RTAUDIO_INPUT_OVERFLOW) std::cout << "Input overflow at " << streamTime << std::endl; if (status == RTAUDIO_OUTPUT_UNDERFLOW) std::cout << "Output underflow at " << streamTime << std::endl; } // Copy input directly to output (passthrough with zero latency) unsigned int channels = 2; unsigned int bytes = nBufferFrames * channels * sizeof(float); memcpy(outputBuffer, inputBuffer, bytes); return 0; } int main() { RtAudio audio; if (audio.getDeviceCount() < 1) { std::cerr << "No audio devices found!" << std::endl; return 1; } // Configure input and output parameters RtAudio::StreamParameters inputParams; inputParams.deviceId = audio.getDefaultInputDevice(); inputParams.nChannels = 2; inputParams.firstChannel = 0; RtAudio::StreamParameters outputParams; outputParams.deviceId = audio.getDefaultOutputDevice(); outputParams.nChannels = 2; outputParams.firstChannel = 0; unsigned int sampleRate = 44100; unsigned int bufferFrames = 256; // Options for low latency duplex RtAudio::StreamOptions options; options.flags = RTAUDIO_MINIMIZE_LATENCY | RTAUDIO_HOG_DEVICE; options.numberOfBuffers = 2; options.priority = 99; // High priority for realtime // Open duplex stream RtAudioErrorType error = audio.openStream(&outputParams, &inputParams, RTAUDIO_FLOAT32, sampleRate, &bufferFrames, &duplexCallback, nullptr, &options); if (error != RTAUDIO_NO_ERROR) { std::cerr << "Error: " << audio.getErrorText() << std::endl; return 1; } std::cout << "Duplex stream opened" << std::endl; std::cout << "Buffer size: " << bufferFrames << " frames" << std::endl; std::cout << "Total latency: " << audio.getStreamLatency() << " frames (" << (audio.getStreamLatency() * 1000.0 / sampleRate) << " ms)" << std::endl; // Start duplex stream error = audio.startStream(); if (error != RTAUDIO_NO_ERROR) { std::cerr << "Error: " << audio.getErrorText() << std::endl; audio.closeStream(); return 1; } std::cout << "Audio passthrough active. Press Enter to stop..." << std::endl; std::cin.get(); // Stop and close if (audio.isStreamRunning()) audio.stopStream(); if (audio.isStreamOpen()) audio.closeStream(); return 0; } ``` -------------------------------- ### RtAudio Build with Meson (Shell) Source: https://github.com/thestk/rtaudio/blob/master/README.md Instructions for building RtAudio with Meson. This involves initializing the build environment with `meson build`, changing into the build directory, and then using `ninja` to perform the compilation. ```bash meson build cd build ninja ``` -------------------------------- ### Export RtAudio Library Targets for Build and Install Trees Source: https://github.com/thestk/rtaudio/blob/master/CMakeLists.txt Exports the RtAudio library targets to be used by other CMake projects. This includes exporting targets for both the build tree (for in-source builds) and the install tree (for installed projects), ensuring proper namespace usage. ```cmake # Export library target (build-tree). export(EXPORT RtAudioTargets NAMESPACE RtAudio::) # Export library target (install-tree). install(EXPORT RtAudioTargets DESTINATION ${RTAUDIO_CMAKE_DESTINATION} NAMESPACE RtAudio::) ``` -------------------------------- ### RtAudio Build with CMake (Shell) Source: https://github.com/thestk/rtaudio/blob/master/README.md This demonstrates building RtAudio using CMake. It involves creating a build directory, changing into it, running CMake to configure the build, and then using `make` to compile the project. ```bash mkdir build cd build cmake .. make ``` -------------------------------- ### RtAudio Build with Autotools (Shell) Source: https://github.com/thestk/rtaudio/blob/master/README.md This command sequence shows how to build RtAudio using the autotools build system. It first runs `autogen.sh` (typically for development versions from git) to generate configuration scripts, followed by `make` to compile the library. ```bash ./autogen.sh make ``` -------------------------------- ### RtAudio C Interface: Basic Audio Playback Source: https://context7.com/thestk/rtaudio/llms.txt This C code demonstrates the fundamental usage of the RtAudio library for audio playback. It initializes RtAudio, configures output parameters, sets up a callback function for generating audio data (a simple square wave in this case), and manages the audio stream lifecycle. Error handling and stream information retrieval are also included. The main dependencies are the RtAudio C header ('rtaudio_c.h') and standard C libraries. ```c #include "rtaudio_c.h" #include #include #include // C-style callback function int audio_callback(void *out, void *in, unsigned int nFrames, double streamTime, rtaudio_stream_status_t status, void *userdata) { float *output = (float *)out; int *frame_count = (int *)userdata; if (status & RTAUDIO_STATUS_OUTPUT_UNDERFLOW) printf("Underflow detected\n"); // Generate simple square wave for (unsigned int i = 0; i < nFrames * 2; i++) { output[i] = ((*frame_count / 100) % 2) ? 0.3f : -0.3f; (*frame_count)++; } return 0; } void error_callback(rtaudio_error_t err, const char *msg) { printf("RtAudio Error: %s\n", msg); } int main() { rtaudio_t audio; rtaudio_stream_parameters_t output_params; rtaudio_stream_options_t options; unsigned int buffer_frames = 512; unsigned int sample_rate = 44100; int frame_count = 0; // Print version printf("RtAudio version: %s\n", rtaudio_version()); // Create audio instance audio = rtaudio_create(RTAUDIO_API_UNSPECIFIED); if (audio == NULL) { printf("Failed to create RtAudio instance\n"); return 1; } // Check device count int device_count = rtaudio_device_count(audio); printf("Found %d audio devices\n", device_count); if (device_count < 1) { rtaudio_destroy(audio); return 1; } // Configure output parameters memset(&output_params, 0, sizeof(output_params)); output_params.device_id = rtaudio_get_default_output_device(audio); output_params.num_channels = 2; output_params.first_channel = 0; // Configure stream options memset(&options, 0, sizeof(options)); options.flags = RTAUDIO_FLAGS_MINIMIZE_LATENCY; options.num_buffers = 2; strncpy(options.name, "C API Test", MAX_NAME_LENGTH - 1); // Open stream rtaudio_error_t err = rtaudio_open_stream( audio, &output_params, NULL, // no input RTAUDIO_FORMAT_FLOAT32, sample_rate, &buffer_frames, audio_callback, &frame_count, &options, error_callback ); if (err != RTAUDIO_ERROR_NONE) { printf("Error opening stream: %s\n", rtaudio_error(audio)); rtaudio_destroy(audio); return 1; } printf("Stream opened with buffer size: %u\n", buffer_frames); // Start stream err = rtaudio_start_stream(audio); if (err != RTAUDIO_ERROR_NONE) { printf("Error starting stream: %s\n", rtaudio_error(audio)); rtaudio_close_stream(audio); rtaudio_destroy(audio); return 1; } printf("Playing for 2 seconds...\n"); #ifdef WIN32 Sleep(2000); #else usleep(2000000); #endif // Check stream status if (rtaudio_is_stream_running(audio)) { double stream_time = rtaudio_get_stream_time(audio); long latency = rtaudio_get_stream_latency(audio); printf("Stream time: %.2f seconds, Latency: %ld frames\n", stream_time, latency); rtaudio_stop_stream(audio); } // Cleanup rtaudio_close_stream(audio); rtaudio_destroy(audio); return 0; } ``` -------------------------------- ### Configure ASIO Backend Source: https://github.com/thestk/rtaudio/blob/master/meson_options.txt Enable or disable the build with ASIO (Audio Stream Input/Output) backend support. This is primarily for Windows systems requiring low-latency audio drivers. ```text option('asio', type : 'feature', value : 'auto', description: 'Build with ASIO Backend') ``` -------------------------------- ### Configure API Documentation Generation Source: https://github.com/thestk/rtaudio/blob/master/meson_options.txt Control whether API documentation is generated during the build process. This is a boolean option, typically set to false by default. ```text option('docs', type : 'boolean', value : 'false', description: 'Generate API documentation') ``` -------------------------------- ### ASIO API Configuration Source: https://github.com/thestk/rtaudio/blob/master/CMakeLists.txt Enables support for the ASIO audio API on Windows. This includes adding ASIO-specific source files, defining the preprocessor macro, and listing the API. ```cmake if (RTAUDIO_API_ASIO) set(NEED_WIN32LIBS ON) include_directories(include) list(APPEND rtaudio_SOURCES include/asio.cpp include/asiodrivers.cpp include/asiolist.cpp include/iasiothiscallresolver.cpp) list(APPEND API_DEFS "-D__WINDOWS_ASIO__") list(APPEND API_LIST "asio") endif() ```