-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathaudiobeep.cpp
66 lines (54 loc) · 1.65 KB
/
audiobeep.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include "audiobeep.h"
#define _USE_MATH_DEFINES
#include <math.h>
// constructor
AudioBeep::AudioBeep(QObject *w, float duration, float frequency, float volume) {
qparent = w;
// 16 bit audio PCM
audioFormat.setSampleRate(sampleRate);
audioFormat.setChannelCount(1);
audioFormat.setSampleSize(16);
audioFormat.setCodec("audio/pcm");
audioFormat.setByteOrder((QAudioFormat::Endian)QSysInfo::ByteOrder);
audioFormat.setSampleType(QAudioFormat::SignedInt);
// check if we can play it
QAudioDeviceInfo deviceInfo(QAudioDeviceInfo::defaultOutputDevice());
if(!deviceInfo.isFormatSupported(audioFormat)) {
return;
}
// number of data samples
const unsigned int n = (unsigned int)round(duration * sampleRate);
// resize byteBuffer to the total number of bytes that will be needed to accommodate
// all the n data samples that are of type float
byteBuffer.resize(sizeof(qint16) * n);
// create the sinewave
for (unsigned int i = 0; i < n; i++) {
// create sine wave data samples, one at a time
qint16 sinVal = (qint16)(sin(2.0 * M_PI * frequency * i / sampleRate)*32767*volume);
( (qint16*)byteBuffer.constData() )[i] = sinVal;
}
// create the fake streaming buffer
input = new QBuffer(&byteBuffer, qparent);
// open the fake stream
input->open(QIODevice::ReadOnly);
// open the audio output
audio = new QAudioOutput(audioFormat, qparent);
}
// destructor
AudioBeep::~AudioBeep() {
if (nullptr != input) {
input->close();
delete input;
}
if (nullptr != audio) {
delete audio;
}
}
// play the audio
void AudioBeep::play() {
if ((nullptr != input) && (nullptr != audio)) {
input->seek(0);
audio->reset();
audio->start(input);
}
}