tonegenerator.cpp Example File
multimedia/spectrum/app/tonegenerator.cpp
#include "spectrum.h"
#include "utils.h"
#include <QByteArray>
#include <QAudioFormat>
#include <qmath.h>
#include <qendian.h>
void generateTone(const SweptTone &tone, const QAudioFormat &format, QByteArray &buffer)
{
Q_ASSERT(isPCMS16LE(format));
const int channelBytes = format.sampleSize() / 8;
const int sampleBytes = format.channelCount() * channelBytes;
int length = buffer.size();
const int numSamples = buffer.size() / sampleBytes;
Q_ASSERT(length % sampleBytes == 0);
Q_UNUSED(sampleBytes)
unsigned char *ptr = reinterpret_cast<unsigned char *>(buffer.data());
qreal phase = 0.0;
const qreal d = 2 * M_PI / format.sampleRate();
const qreal startFreq = tone.startFreq ? tone.startFreq : 1.0;
qreal phaseStep = d * startFreq;
const qreal phaseStepStep = d * (tone.endFreq - startFreq) / numSamples;
while (length) {
const qreal x = tone.amplitude * qSin(phase);
const qint16 value = realToPcm(x);
for (int i=0; i<format.channelCount(); ++i) {
qToLittleEndian<qint16>(value, ptr);
ptr += channelBytes;
length -= channelBytes;
}
phase += phaseStep;
while (phase > 2 * M_PI)
phase -= 2 * M_PI;
phaseStep += phaseStepStep;
}
}