QByteArray包括浮点数

时间:2019-03-19 16:39:49

标签: c++ qt qbytearray qbuffer

我是C ++和QT的新手,实际上我正在编写一个声音信号发生器。但是我的问题是,

我正在创建要在qbytearray中实现的浮点数,我将用它来填充qbuffer。但是我无法浮动到qbytearray中,它给出警告说“丢失精度”。而且qbytearray仅包含从-100到100的整数值。我需要具有所需精度的浮点数。

你能帮我吗?

void MainWindow::toneGenerate(){

    int len= m_seconds*SAMPLE_RATE;

    sinbuf.resize(len);

    for(int i=0;i<len;i++){
        qreal t = m_freq*i;
        t *= FREQ_CONST;
        t = t+ m_ph;
        t = qSin(t);
        t*= m_amp;

        sinbuf[i] = t;
    }

    sininput.setBuffer(&sinbuf);
    sininput.open(QIODevice::ReadWrite);
}

2 个答案:

答案 0 :(得分:0)

为声音开发编写代码时,请务必注意每个样本的大小,将样本存储为二进制数据的字节顺序,以及是否有必要向数据写入标头(如果是原始标头) -更少。

如果您的目标是完成QBuffer,则可以通过QDataStream对其进行写操作,如果愿意,可以将其读回。

在我的回答中,我假设使用Little Endian,而不是浮点数,而是使用16位带符号整数采样,1个通道和8000Hz频率。

我提供了一个简单的声音发生器示例,请根据您的需要进行调整!

让我们看下面的控制台示例:

#include <QtCore>
#include <QtMultimedia>

static QBuffer m_float_buffer;

void toneGenerator()
{
    QDataStream write_stream(&m_float_buffer);
    write_stream.setVersion(QDataStream::Qt_5_0); //Protocol for version 5.0
    write_stream.setByteOrder(QDataStream::LittleEndian);

    //Tone generator from http://www.cplusplus.com/forum/general/129827/

    const unsigned int samplerate = 8000;
    const unsigned short channels = 1;

    const double pi = M_PI;
    const qint16 amplitude = qint16(INT16_MAX * 0.5);

    const unsigned short n_frequencies = 8;
    const unsigned short n_seconds_each = 1;

    float frequencies[n_frequencies] = {55.0, 110.0, 220.0, 440.0, 880.0, 1760.0, 3520.0, 7040.0};

    const int n_samples = channels * samplerate * n_frequencies * n_seconds_each;

    int index = n_samples / n_frequencies;

    for (unsigned short i = 0; i < n_frequencies; i++)
    {
        float freq = frequencies[i];
        float d = (samplerate / freq);
        int c = 0;

        for (int j = index * i; j < index * (i + 1); j++)
        {
            float deg = 360.0f / d;
            write_stream << qint16(qSin((c++ * double(deg)) * pi / 180.0) * amplitude);
        }
    }
}

void dataPlay()
{
    QAudioFormat format;
    format.setCodec("audio/pcm");
    format.setSampleRate(8000);
    format.setChannelCount(1);
    format.setSampleSize(16);
    format.setByteOrder(QAudioFormat::LittleEndian);
    format.setSampleType(QAudioFormat::SignedInt);

    QAudioDeviceInfo info(QAudioDeviceInfo::defaultOutputDevice());

    if (!info.isFormatSupported(format))
    {
        qDebug() << "Raw audio format not supported by backend, cannot play audio.";
        return;
    }

    QAudioOutput audio(format);

    QEventLoop loop;

    QObject::connect(&audio, &QAudioOutput::stateChanged, &audio, [&](const QAudio::State state){
        if (state != QAudio::ActiveState)
            loop.quit();
    });

    audio.start(&m_float_buffer);

    loop.exec();
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    qDebug() << "Opening buffer...";

    m_float_buffer.open(QBuffer::ReadWrite);

    qDebug() << "\nGenerating...";
    toneGenerator();

    //Back to beginning, now for reading
    m_float_buffer.seek(0);

    qDebug() << "\nPlaying...";
    dataPlay();

    qDebug() << "\nQBuffer size:" << m_float_buffer.size() << "bytes";

    return a.exec();
}

答案 1 :(得分:0)

[]上的QByteArray运算符仅引用一个字节(长8位),而浮点数是4个字节(长32位)。

您应该存储将存储所有32位的整个浮点数,而不是sinbuf[i] = t;来存储浮点数的前8位。

此模板函数将返回一个QByteArray,您可以将其附加到sinbuf

template<typename T>
static QByteArray numToByteArray(T num, bool isLE = false)
{
    QByteArray ba("");
    if(isLE){
        ba.resize(sizeof(T));
        memcpy(ba.data(), &num, sizeof(T));
    }
    else{
        for(int i=sizeof(T)-1; i>=0; i--)
            ba.append(quint8(num>>(i*8)));
    }

    return ba;
}

用法:

void MainWindow::toneGenerate(){

    int len= m_seconds*SAMPLE_RATE;

    //sinbuf.resize(len); calls to append will resize for you

    for(int i=0;i<len;i++){
        qreal t = m_freq*i;
        t *= FREQ_CONST;
        t = t+ m_ph;
        t = qSin(t);
        t*= m_amp;

        //You will have to account for endianness
        //Pass true as a second argument here if it's Little Endian
        sinbuf.append(numToByteArray<float>(t));
    }

    sininput.setBuffer(&sinbuf);
    sininput.open(QIODevice::ReadWrite);

    //You will want to write directly to the device stream
    //because sinbuf will store everything in memory
}

当然,这完全取决于样本大小和字节序...