Skip to content

Instantly share code, notes, and snippets.

@davesnowdon
Created December 31, 2022 12:16
Show Gist options
  • Save davesnowdon/1ec5182933f431b7688f21154141303b to your computer and use it in GitHub Desktop.
Save davesnowdon/1ec5182933f431b7688f21154141303b to your computer and use it in GitHub Desktop.
Can you help me write a C++ program that reads blocks of audio data from the microphone using the ALSA driver?
#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);
snd_pcm_hw_params_set_rate_near(handle, params, 44100, 0);
snd_pcm_hw_params_set_channels(handle, params, 2);
// 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 this generated code the usage of the snd_pcm_hw_params_set_rate_near is incorrect as the function has the following declaration
int snd_pcm_hw_params_set_rate_near(snd_pcm_t*, snd_pcm_hw_params_t*, unsigned int*, int*)

ChatGPT fixed this when I asked it to add error checking https://gist.github.com/davesnowdon/34c2d661240e781a4c2c3a6f0ae982e7

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