Qt 5.1 or later:
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, ..
The easiest way is to use files (WAV, MP3, ..), eg as described here: How to play sound with Qt But then I have to generate such files for each of my scenarios.
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?
So what is the easiest way to just play frequency x for n milliseconds?
To generate a tone in Qt, we can pass our own QBuffer to the QAudioOutput to be played.
Take a look at the first example on the QAudioOutput page.
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 .
You could use the "window.h" package (not a QT one). Then you just use the Beep(frequency, miliseconds). For your example it should be Beep(1000,2000) and Beep(3000,1000) respectively.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.