Hi, I'm trying to capture audio from a microphone into a vector in C++. I'm using openAL's example code Capture.cpp (below). I understand that it buffer's the data, but I'm not sure what comes after.

In short, what do I do to put the buffer's data into a normalized (+/- 1) vector of floats?

#include <al.h>
#include <alc.h>
#include <iostream>
using namespace std;

const int SRATE = 44100;
const int SSIZE = 1024;

ALbyte buffer[22050];
ALint sample;

int main(int argc, char *argv[]) {
    alGetError();
    ALCdevice *device = alcCaptureOpenDevice(NULL, SRATE, AL_FORMAT_STEREO16, SSIZE);
    if (alGetError() != AL_NO_ERROR) {
        return 0;
    }
    alcCaptureStart(device);

    while (true) {
        alcGetIntegerv(device, ALC_CAPTURE_SAMPLES, (ALCsizei)sizeof(ALint), &sample);
        alcCaptureSamples(device, (ALCvoid *)buffer, sample);



        // ... do something with the buffer 

    }

    alcCaptureStop(device);
    alcCaptureCloseDevice(device);

    return 0;
}

Well it looks like you've done enough to get a buffer of ALint values. What is the range of possible valid values in that buffer? Then normalizing to float is as simple as:

float intermediate_value = (i_val - min_ival)/float(max_ival - min_ival);
float f_val = min_fval + intermediate_value*(max_fval - min_fval);

If the integers, for example, all lie between 0 and 65535 (16 bit unsigned integers), and you want floats between -1 and 1, then the values are

int min_ival = 0;
int max_ival = 65535;
float min_fval = -1.0f;
float max_fval = 1.0f;

Keep in mind: expressions which don't change can be evaluated once, and multiplication is often faster than division. Though a really good optimizing compiler will take care of it for you.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.