Created
December 31, 2022 12:17
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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(¶ms); | |
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In a follow up request, ChatGPT also generated the CMakeLists.txt file to build the code: