Skip to content

Instantly share code, notes, and snippets.

@malikzh
Last active March 10, 2023 16:07
Show Gist options
  • Select an option

  • Save malikzh/044ff9007144df43c1d82f5c09ed47ad to your computer and use it in GitHub Desktop.

Select an option

Save malikzh/044ff9007144df43c1d82f5c09ed47ad to your computer and use it in GitHub Desktop.
Android AAudio example sine signal in C++
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <aaudio/AAudio.h>
constexpr int32_t kSampleRate = 48000;
constexpr double f1 = 440.0; // Hz
constexpr double f2 = 554.37; // Hz
constexpr double f3 = 659.26; // Hz
AAudioStream* gStream = nullptr;
uint32_t t = 0;
static inline int16_t clamp_sample(int32_t sample) {
if (sample > 32767) {
return 32767;
}
if (sample < -32767) {
return -32767;
}
return (int16_t)sample;
}
// Callback function to fill the buffer with sine wave samples
aaudio_data_callback_result_t DataCallback(
AAudioStream* stream, void* userData, void* audioData, int32_t length) {
int16_t *buf = (int16_t*)audioData;
for (size_t i=0 ; i<length; ++i) {
buf[i] = (int16_t)(8000.0 * sin(2.0 * M_PI * f1 * ((double)t / (double)kSampleRate)));
buf[i] = clamp_sample((int32_t)buf[i] + (int32_t)(8000.0 * sin(2.0 * M_PI * f2 * ((double)t / (double)kSampleRate))));
buf[i] = clamp_sample((int32_t)buf[i] + (int32_t)(8000.0 * sin(2.0 * M_PI * f3 * ((double)t / (double)kSampleRate))));
t++;
}
return AAUDIO_CALLBACK_RESULT_CONTINUE;
}
// Start playing the sine wave
void Start() {
AAudioStreamBuilder* builder = nullptr;
AAudio_createStreamBuilder(&builder);
AAudioStreamBuilder_setFormat(builder, AAUDIO_FORMAT_PCM_I16);
AAudioStreamBuilder_setChannelCount(builder, 1);
AAudioStreamBuilder_setSampleRate(builder, kSampleRate);
AAudioStreamBuilder_setDataCallback(builder, DataCallback, nullptr);
AAudioStreamBuilder_setPerformanceMode(builder, AAUDIO_PERFORMANCE_MODE_LOW_LATENCY);
if (AAudioStreamBuilder_openStream(builder, &gStream) != AAUDIO_OK) {
AAudioStreamBuilder_delete(builder);
return;
}
AAudioStreamBuilder_delete(builder);
AAudioStream_requestStart(gStream);
}
// Stop playing the sine wave
void Stop() {
AAudioStream_requestStop(gStream);
AAudioStream_close(gStream);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment