gpt4 book ai didi

c++ - 在 Qt 中播放通知(频率 x)声音 - 最简单的方法?

转载 作者:搜寻专家 更新时间:2023-10-31 01:06:10 24 4
gpt4 key购买 nike

Qt 5.1 或更高版本:

我需要播放一个频率为 x 的通知声音 n 毫秒。如果我能像这样组合音调也很好:1000Hz 持续 2 秒,然后 3000Hz 持续 1 秒,..

最简单的方法是使用文件(WAV、MP3、..),例如如此处所述:How to play sound with Qt但是我必须为我的每个场景生成这样的文件。

Qt's audio output example在内存中生成此类音调(Generator::generateData(const QAudioFormat &format, qint64 durationUs, int sampleRate))。我可以为我的目的编写这样一个生成器。但我必须这样做吗?

那么只播放 n 毫秒频率 x 的最简单方法是什么?

最佳答案

要在 Qt 中生成音调,我们可以将我们自己的 QBuffer 传递给要播放的 QAudioOutput。

看看 first example在 QAudioOutput 页面上。

我所做的是在 QByteArray 中创建我的波形。请记住,sin(2 * pi * frequency * i/sample_rate) 将为您提供所需频率的 sin 音调:

#define FREQ_CONST ((2.0 * M_PI) / SAMPLE_RATE)

QByteArray* bytebuf = new QByteArray();
buf->resize(seconds * SAMPLE_RATE);

for (int i=0; i<(seconds * SAMPLE_RATE); i++) {
qreal t = (qreal)(freq * i);
t = t * FREQ_CONST;
t = qSin(t);
// now we normalize t
t *= TG_MAX_VAL;
(*bytebuf)[i] = (quint8)t;
}

然后我们可以获取该缓冲区并执行如下操作来播放它:

// Make a QBuffer from our QByteArray
QBuffer* input = new QBuffer(bytebuf);
input->open(QIODevice::ReadOnly);

// Create an output with our premade QAudioFormat (See example in QAudioOutput)
QAudioOutput* audio = new QAudioOutput(format, this);
audio->start(input);

如果您需要更多示例代码,您可以在我刚刚开始的一个小项目中看到我是如何做到的 here .

关于c++ - 在 Qt 中播放通知(频率 x)声音 - 最简单的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21310324/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com