source: trunk/examples/multimedia/audiooutput/audiooutput.cpp@ 846

Last change on this file since 846 was 846, checked in by Dmitry A. Kuminov, 14 years ago

trunk: Merged in qt 4.7.2 sources from branches/vendor/nokia/qt.

  • Property svn:eol-style set to native
File size: 10.4 KB
Line 
1/****************************************************************************
2**
3** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
4** All rights reserved.
5** Contact: Nokia Corporation (qt-info@nokia.com)
6**
7** This file is part of the examples of the Qt Toolkit.
8**
9** $QT_BEGIN_LICENSE:BSD$
10** You may use this file under the terms of the BSD license as follows:
11**
12** "Redistribution and use in source and binary forms, with or without
13** modification, are permitted provided that the following conditions are
14** met:
15** * Redistributions of source code must retain the above copyright
16** notice, this list of conditions and the following disclaimer.
17** * Redistributions in binary form must reproduce the above copyright
18** notice, this list of conditions and the following disclaimer in
19** the documentation and/or other materials provided with the
20** distribution.
21** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor
22** the names of its contributors may be used to endorse or promote
23** products derived from this software without specific prior written
24** permission.
25**
26** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
27** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
28** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
29** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
30** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
31** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
32** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
33** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
34** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
35** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
36** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
37** $QT_END_LICENSE$
38**
39****************************************************************************/
40
41#include <QDebug>
42#include <QVBoxLayout>
43
44#include <QAudioOutput>
45#include <QAudioDeviceInfo>
46#include <QtCore/qmath.h>
47#include <QtCore/qendian.h>
48#include "audiooutput.h"
49
50const QString AudioTest::PushModeLabel(tr("Enable push mode"));
51const QString AudioTest::PullModeLabel(tr("Enable pull mode"));
52const QString AudioTest::SuspendLabel(tr("Suspend playback"));
53const QString AudioTest::ResumeLabel(tr("Resume playback"));
54
55const int DurationSeconds = 1;
56const int ToneFrequencyHz = 600;
57const int DataFrequencyHz = 44100;
58const int BufferSize = 32768;
59
60
61Generator::Generator(const QAudioFormat &format,
62 qint64 durationUs,
63 int frequency,
64 QObject *parent)
65 : QIODevice(parent)
66 , m_pos(0)
67{
68 generateData(format, durationUs, frequency);
69}
70
71Generator::~Generator()
72{
73
74}
75
76void Generator::start()
77{
78 open(QIODevice::ReadOnly);
79}
80
81void Generator::stop()
82{
83 m_pos = 0;
84 close();
85}
86
87void Generator::generateData(const QAudioFormat &format, qint64 durationUs, int frequency)
88{
89 const int channelBytes = format.sampleSize() / 8;
90 const int sampleBytes = format.channels() * channelBytes;
91
92 qint64 length = (format.frequency() * format.channels() * (format.sampleSize() / 8))
93 * durationUs / 100000;
94
95 Q_ASSERT(length % sampleBytes == 0);
96 Q_UNUSED(sampleBytes) // suppress warning in release builds
97
98 m_buffer.resize(length);
99 unsigned char *ptr = reinterpret_cast<unsigned char *>(m_buffer.data());
100 int sampleIndex = 0;
101
102 while (length) {
103 const qreal x = qSin(2 * M_PI * frequency * qreal(sampleIndex % format.frequency()) / format.frequency());
104 for (int i=0; i<format.channels(); ++i) {
105 if (format.sampleSize() == 8 && format.sampleType() == QAudioFormat::UnSignedInt) {
106 const quint8 value = static_cast<quint8>((1.0 + x) / 2 * 255);
107 *reinterpret_cast<quint8*>(ptr) = value;
108 } else if (format.sampleSize() == 8 && format.sampleType() == QAudioFormat::SignedInt) {
109 const qint8 value = static_cast<qint8>(x * 127);
110 *reinterpret_cast<quint8*>(ptr) = value;
111 } else if (format.sampleSize() == 16 && format.sampleType() == QAudioFormat::UnSignedInt) {
112 quint16 value = static_cast<quint16>((1.0 + x) / 2 * 65535);
113 if (format.byteOrder() == QAudioFormat::LittleEndian)
114 qToLittleEndian<quint16>(value, ptr);
115 else
116 qToBigEndian<quint16>(value, ptr);
117 } else if (format.sampleSize() == 16 && format.sampleType() == QAudioFormat::SignedInt) {
118 qint16 value = static_cast<qint16>(x * 32767);
119 if (format.byteOrder() == QAudioFormat::LittleEndian)
120 qToLittleEndian<qint16>(value, ptr);
121 else
122 qToBigEndian<qint16>(value, ptr);
123 }
124
125 ptr += channelBytes;
126 length -= channelBytes;
127 }
128 ++sampleIndex;
129 }
130}
131
132qint64 Generator::readData(char *data, qint64 len)
133{
134 qint64 total = 0;
135 while (len - total > 0) {
136 const qint64 chunk = qMin((m_buffer.size() - m_pos), len - total);
137 memcpy(data + total, m_buffer.constData() + m_pos, chunk);
138 m_pos = (m_pos + chunk) % m_buffer.size();
139 total += chunk;
140 }
141 return total;
142}
143
144qint64 Generator::writeData(const char *data, qint64 len)
145{
146 Q_UNUSED(data);
147 Q_UNUSED(len);
148
149 return 0;
150}
151
152qint64 Generator::bytesAvailable() const
153{
154 return m_buffer.size() + QIODevice::bytesAvailable();
155}
156
157AudioTest::AudioTest()
158 : m_pullTimer(new QTimer(this))
159 , m_modeButton(0)
160 , m_suspendResumeButton(0)
161 , m_deviceBox(0)
162 , m_device(QAudioDeviceInfo::defaultOutputDevice())
163 , m_generator(0)
164 , m_audioOutput(0)
165 , m_output(0)
166 , m_buffer(BufferSize, 0)
167{
168 initializeWindow();
169 initializeAudio();
170}
171
172void AudioTest::initializeWindow()
173{
174 QScopedPointer<QWidget> window(new QWidget);
175 QScopedPointer<QVBoxLayout> layout(new QVBoxLayout);
176
177 m_deviceBox = new QComboBox(this);
178 foreach (const QAudioDeviceInfo &deviceInfo, QAudioDeviceInfo::availableDevices(QAudio::AudioOutput))
179 m_deviceBox->addItem(deviceInfo.deviceName(), qVariantFromValue(deviceInfo));
180 connect(m_deviceBox,SIGNAL(activated(int)),SLOT(deviceChanged(int)));
181 layout->addWidget(m_deviceBox);
182
183 m_modeButton = new QPushButton(this);
184 m_modeButton->setText(PushModeLabel);
185 connect(m_modeButton, SIGNAL(clicked()), SLOT(toggleMode()));
186 layout->addWidget(m_modeButton);
187
188 m_suspendResumeButton = new QPushButton(this);
189 m_suspendResumeButton->setText(SuspendLabel);
190 connect(m_suspendResumeButton, SIGNAL(clicked()), SLOT(toggleSuspendResume()));
191 layout->addWidget(m_suspendResumeButton);
192
193 window->setLayout(layout.data());
194 layout.take(); // ownership transferred
195
196 setCentralWidget(window.data());
197 QWidget *const windowPtr = window.take(); // ownership transferred
198 windowPtr->show();
199}
200
201void AudioTest::initializeAudio()
202{
203 connect(m_pullTimer, SIGNAL(timeout()), SLOT(pullTimerExpired()));
204
205 m_pullMode = true;
206
207 m_format.setFrequency(DataFrequencyHz);
208 m_format.setChannels(1);
209 m_format.setSampleSize(16);
210 m_format.setCodec("audio/pcm");
211 m_format.setByteOrder(QAudioFormat::LittleEndian);
212 m_format.setSampleType(QAudioFormat::SignedInt);
213
214 QAudioDeviceInfo info(QAudioDeviceInfo::defaultOutputDevice());
215 if (!info.isFormatSupported(m_format)) {
216 qWarning() << "Default format not supported - trying to use nearest";
217 m_format = info.nearestFormat(m_format);
218 }
219
220 m_generator = new Generator(m_format, DurationSeconds*1000000, ToneFrequencyHz, this);
221
222 createAudioOutput();
223}
224
225void AudioTest::createAudioOutput()
226{
227 delete m_audioOutput;
228 m_audioOutput = 0;
229 m_audioOutput = new QAudioOutput(m_device, m_format, this);
230 connect(m_audioOutput, SIGNAL(notify()), SLOT(notified()));
231 connect(m_audioOutput, SIGNAL(stateChanged(QAudio::State)), SLOT(stateChanged(QAudio::State)));
232 m_generator->start();
233 m_audioOutput->start(m_generator);
234}
235
236AudioTest::~AudioTest()
237{
238
239}
240
241void AudioTest::deviceChanged(int index)
242{
243 m_pullTimer->stop();
244 m_generator->stop();
245 m_audioOutput->stop();
246 m_audioOutput->disconnect(this);
247 m_device = m_deviceBox->itemData(index).value<QAudioDeviceInfo>();
248 createAudioOutput();
249}
250
251void AudioTest::notified()
252{
253 qWarning() << "bytesFree = " << m_audioOutput->bytesFree()
254 << ", " << "elapsedUSecs = " << m_audioOutput->elapsedUSecs()
255 << ", " << "processedUSecs = " << m_audioOutput->processedUSecs();
256}
257
258void AudioTest::pullTimerExpired()
259{
260 if (m_audioOutput && m_audioOutput->state() != QAudio::StoppedState) {
261 int chunks = m_audioOutput->bytesFree()/m_audioOutput->periodSize();
262 while (chunks) {
263 const qint64 len = m_generator->read(m_buffer.data(), m_audioOutput->periodSize());
264 if (len)
265 m_output->write(m_buffer.data(), len);
266 if (len != m_audioOutput->periodSize())
267 break;
268 --chunks;
269 }
270 }
271}
272
273void AudioTest::toggleMode()
274{
275 m_pullTimer->stop();
276 m_audioOutput->stop();
277
278 if (m_pullMode) {
279 m_modeButton->setText(PullModeLabel);
280 m_output = m_audioOutput->start();
281 m_pullMode = false;
282 m_pullTimer->start(20);
283 } else {
284 m_modeButton->setText(PushModeLabel);
285 m_pullMode = true;
286 m_audioOutput->start(m_generator);
287 }
288
289 m_suspendResumeButton->setText(SuspendLabel);
290}
291
292void AudioTest::toggleSuspendResume()
293{
294 if (m_audioOutput->state() == QAudio::SuspendedState) {
295 qWarning() << "status: Suspended, resume()";
296 m_audioOutput->resume();
297 m_suspendResumeButton->setText(SuspendLabel);
298 } else if (m_audioOutput->state() == QAudio::ActiveState) {
299 qWarning() << "status: Active, suspend()";
300 m_audioOutput->suspend();
301 m_suspendResumeButton->setText(ResumeLabel);
302 } else if (m_audioOutput->state() == QAudio::StoppedState) {
303 qWarning() << "status: Stopped, resume()";
304 m_audioOutput->resume();
305 m_suspendResumeButton->setText(SuspendLabel);
306 } else if (m_audioOutput->state() == QAudio::IdleState) {
307 qWarning() << "status: IdleState";
308 }
309}
310
311void AudioTest::stateChanged(QAudio::State state)
312{
313 qWarning() << "state = " << state;
314}
Note: See TracBrowser for help on using the repository browser.