在Qt中播放通知(频率x)声音-最简单的方法? [英] Play notification (frequency x) sound in Qt - easiest way?
问题描述
Qt 5.1或更高版本:
Qt 5.1 or later:
我需要播放x频率的通知声音n毫秒.如果我可以将这样的音调组合起来也很不错:1000Hz持续2秒,然后3000Hz持续1秒,..
I need to play a notification sound of frequency x for n milliseconds. It'd also be nice if I could combine tones like this: 1000Hz for 2 secs, then 3000Hz for 1 sec, ..
最简单的方法是使用文件(WAV,MP3等),例如如下所述:如何使用Qt播放声音但是我必须生成这些文件适用于我的每种情况.
The easiest way is to use files (WAV, MP3, ..), e.g. as described here: How to play sound with Qt But then I have to generate such files for each of my scenarios.
Qt音频输出示例在内存(Generator::generateData(const QAudioFormat &format, qint64 durationUs, int sampleRate)
)中生成此类音调.我可以为自己编写这样的生成器.但是我必须吗?
Qt's audio output example generates such tones in memory ( Generator::generateData(const QAudioFormat &format, qint64 durationUs, int sampleRate)
). I could write such a generator for my purpose. But do I have to?
那么播放n毫秒的频率x的最简单方法是什么?
So what is the easiest way to just play frequency x for n milliseconds?
推荐答案
要在Qt中生成音调,我们可以将自己的QBuffer传递给要播放的QAudioOutput.
To generate a tone in Qt, we can pass our own QBuffer to the QAudioOutput to be played.
在QAudioOutput页面上查看第一个示例
Take a look at the first example on the QAudioOutput page.
我所做的是在QByteArray中创建波形.
请记住,sin(2 * pi * frequency * i / sample_rate)
将给您所需频率的正弦音:
What I did was create my waveform in a QByteArray.
Remember that sin(2 * pi * frequency * i / sample_rate)
will give you a sin tone of the desired frequency:
#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;
}
然后我们可以使用该缓冲区并执行以下操作来播放它:
Then we can take that buffer and do something like this to play it:
// 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);
如果您需要更多示例代码,则可以在我刚刚开始的一个小项目中看到我的操作方式.此处.
If you need more example code, you can see how I did it in a little project I just started here.
这篇关于在Qt中播放通知(频率x)声音-最简单的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!