Skip to content

Instantly share code, notes, and snippets.

@davesnowdon
Created December 31, 2022 12:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davesnowdon/34c2d661240e781a4c2c3a6f0ae982e7 to your computer and use it in GitHub Desktop.
Save davesnowdon/34c2d661240e781a4c2c3a6f0ae982e7 to your computer and use it in GitHub Desktop.
please update the code to check for errors in the snd_pcm_hw_params functions
#include <alsa/asoundlib.h>
#include <iostream>
int main() {
// Open the default PCM device
snd_pcm_t *handle;
int error = snd_pcm_open(&handle, "default", SND_PCM_STREAM_CAPTURE, 0);
if (error < 0) {
std::cerr << "Error opening PCM device: " << snd_strerror(error) << std::endl;
return 1;
}
// Set the audio parameters
snd_pcm_hw_params_t *params;
snd_pcm_hw_params_alloca(&params);
snd_pcm_hw_params_any(handle, params);
snd_pcm_hw_params_set_access(handle, params, SND_PCM_ACCESS_RW_INTERLEAVED);
snd_pcm_hw_params_set_format(handle, params, SND_PCM_FORMAT_S16_LE);
// Set the sample rate
unsigned int sampleRate = 44100;
error = snd_pcm_hw_params_set_rate_near(handle, params, &sampleRate, 0);
if (error < 0) {
std::cerr << "Error setting sample rate: " << snd_strerror(error) << std::endl;
return 1;
}
std::cout << "Sample rate set to " << sampleRate << " Hz" << std::endl;
// Set the number of channels
unsigned int channels = 2;
error = snd_pcm_hw_params_set_channels(handle, params, channels);
if (error < 0) {
std::cerr << "Error setting number of channels: " << snd_strerror(error) << std::endl;
return 1;
}
std::cout << "Number of channels set to " << channels << std::endl;
// Set the audio parameters
error = snd_pcm_hw_params(handle, params);
if (error < 0) {
std::cerr << "Error setting PCM parameters: " << snd_strerror(error) << std::endl;
return 1;
}
// Allocate a buffer to hold the audio data
const int bufferSize = 4096;
short buffer[bufferSize];
// Read audio data in a loop
while (true) {
// Read audio data from the microphone
int readCount = snd_pcm_readi(handle, buffer, bufferSize);
if (readCount < 0) {
std::cerr << "Error reading audio data: " << snd_strerror(readCount) << std::endl;
return 1;
}
// Process the audio data here...
}
// Close the PCM device
snd_pcm_close(handle);
return 0;
}
@davesnowdon
Copy link
Author

In a follow up request, ChatGPT also generated the CMakeLists.txt file to build the code:

cmake_minimum_required(VERSION 3.10)
project(alsa_example)

# Find the ALSA library
find_package(ALSA REQUIRED)

# Add the source files
set(SOURCES main.cpp)

# Add the executable
add_executable(alsa_example ${SOURCES})

# Link the executable with the ALSA library
target_link_libraries(alsa_example PRIVATE ${ALSA_LIBRARIES})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment