NDEVR
API Documentation
MicByteBuffer.h
1#pragma once
2#include "DLLInfo.h"
3#ifdef Q_OS_WINDOWS
4#include <QAudioSource>
5#include <QAudioFormat>
6#include <QMediaDevices>
7#include <QIODevice>
8#include <QByteArray>
9#include <QtGlobal>
10namespace NDEVR
11{
15 class NDEVR_SOUND_MANAGER_API MicByteBuffer final : public QObject
16 {
17 Q_OBJECT
18 public:
22 explicit MicByteBuffer(QObject* parent = nullptr)
23 : QObject(parent)
24 {
25 QAudioFormat f;
26 f.setSampleRate(16000);
27 f.setChannelCount(1);
28 f.setSampleFormat(QAudioFormat::Int16);
29
30 const QAudioDevice dev = QMediaDevices::defaultAudioInput();
31 m_format = dev.preferredFormat();
32
33 if (dev.isFormatSupported(f))
34 m_format = f;
35
36 m_source = new QAudioSource(dev, m_format, this);
37 m_source->setBufferSize(4096 * 8);
38 }
39
41 ~MicByteBuffer() override
42 {
43 stop();
44 }
45
47 void start()
48 {
49 if (!m_source)
50 return;
51
52 if (m_io)
53 return;
54
55 m_buffer.clear();
56 m_io = m_source->start();
57 if (!m_io)
58 return;
59
60 connect(m_io, &QIODevice::readyRead, this, &MicByteBuffer::onReadyRead, Qt::DirectConnection);
61 }
62
64 void stop()
65 {
66 if (!m_source)
67 return;
68
69 if (m_io)
70 disconnect(m_io, nullptr, this, nullptr);
71
72 m_source->stop();
73 m_io = nullptr;
74 }
75
79 const QByteArray& bytes() const
80 {
81 return m_buffer;
82 }
83
87 QByteArray takeBytes()
88 {
89 QByteArray out = std::move(m_buffer);
90 m_buffer.clear();
91 return out;
92 }
93
95 void clear()
96 {
97 m_buffer.clear();
98 }
99
103 qint64 bytesCaptured() const
104 {
105 return m_totalBytes;
106 }
107
111 QAudioFormat format() const
112 {
113 return m_format;
114 }
115
116 signals:
121 void bytesAppended(qint64 appendedBytes, qint64 totalBytes);
122
123 private slots:
125 void onReadyRead()
126 {
127 if (!m_io)
128 return;
129
130 const qint64 avail = m_io->bytesAvailable();
131 if (avail <= 0)
132 return;
133
134 m_tmp.resize(int(avail));
135 const qint64 got = m_io->read(m_tmp.data(), m_tmp.size());
136 if (got <= 0)
137 return;
138
139 m_buffer.append(m_tmp.constData(), int(got));
140 m_totalBytes += got;
141
142 emit bytesAppended(got, m_totalBytes);
143 }
144
145 private:
146 QAudioSource* m_source = nullptr;
147 QIODevice* m_io = nullptr;
148 QAudioFormat m_format;
149
150 QByteArray m_buffer;
151 QByteArray m_tmp;
152 qint64 m_totalBytes = 0;
153 };
154}
155#endif
The primary namespace for the NDEVR SDK.