Skip to content

Instantly share code, notes, and snippets.

@davesnowdon
Created December 29, 2022 19:32
Show Gist options
  • Save davesnowdon/f53cfc836c904e00c2e1697a8c7e937d to your computer and use it in GitHub Desktop.
Save davesnowdon/f53cfc836c904e00c2e1697a8c7e937d to your computer and use it in GitHub Desktop.
ChatGPT: Write a C++ program for Linux which reads audio using the ALSA driver and encodes it using FLAC
#include <alsa/asoundlib.h>
#include <flac++/encoder.h>
#include <cstdio>
#include <cstring>
constexpr int kSampleRate = 44100; // Sample rate in Hz
constexpr int kNumChannels = 2; // Number of channels
constexpr int kBufferSize = 4096; // Size of the audio buffer
int main() {
// Open the ALSA audio capture device
snd_pcm_t* capture_handle;
if (snd_pcm_open(&capture_handle, "default", SND_PCM_STREAM_CAPTURE, 0) < 0) {
fprintf(stderr, "Failed to open capture device\n");
return 1;
}
// Set the audio capture parameters
snd_pcm_hw_params_t* hw_params;
snd_pcm_hw_params_alloca(&hw_params);
if (snd_pcm_hw_params_any(capture_handle, hw_params) < 0) {
fprintf(stderr, "Failed to get capture parameters\n");
return 1;
}
if (snd_pcm_hw_params_set_access(capture_handle, hw_params, SND_PCM_ACCESS_RW_INTERLEAVED) < 0) {
fprintf(stderr, "Failed to set interleaved access\n");
return 1;
}
if (snd_pcm_hw_params_set_format(capture_handle, hw_params, SND_PCM_FORMAT_S16_LE) < 0) {
fprintf(stderr, "Failed to set S16 format\n");
return 1;
}
if (snd_pcm_hw_params_set_rate_near(capture_handle, hw_params, &kSampleRate, 0) < 0) {
fprintf(stderr, "Failed to set sample rate\n");
return 1;
}
if (snd_pcm_hw_params_set_channels(capture_handle, hw_params, kNumChannels) < 0) {
fprintf(stderr, "Failed to set number of channels\n");
return 1;
}
if (snd_pcm_hw_params(capture_handle, hw_params) < 0) {
fprintf(stderr, "Failed to set capture parameters\n");
return 1;
}
// Initialize the FLAC encoder
FLAC::Encoder::File encoder;
if (!encoder.is_valid()) {
fprintf(stderr, "Failed to initialize encoder\n");
return 1;
}
encoder.set_sample_rate(kSampleRate);
encoder.set_channels(kNumChannels);
encoder.set_bits_per_sample(16);
@davesnowdon
Copy link
Author

Looks like ChatGPT hit some kind of length limit or just gave up

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