qtmobility/examples/audioinput/audioinput.cpp
changeset 14 6fbed849b4f4
equal deleted inserted replaced
11:06b8e2af4411 14:6fbed849b4f4
       
     1 /****************************************************************************
       
     2 **
       
     3 ** Copyright (C) 2010 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:LGPL$
       
    10 ** No Commercial Usage
       
    11 ** This file contains pre-release code and may not be distributed.
       
    12 ** You may use this file in accordance with the terms and conditions
       
    13 ** contained in the Technology Preview License Agreement accompanying
       
    14 ** this package.
       
    15 **
       
    16 ** GNU Lesser General Public License Usage
       
    17 ** Alternatively, this file may be used under the terms of the GNU Lesser
       
    18 ** General Public License version 2.1 as published by the Free Software
       
    19 ** Foundation and appearing in the file LICENSE.LGPL included in the
       
    20 ** packaging of this file.  Please review the following information to
       
    21 ** ensure the GNU Lesser General Public License version 2.1 requirements
       
    22 ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
       
    23 **
       
    24 ** In addition, as a special exception, Nokia gives you certain additional
       
    25 ** rights.  These rights are described in the Nokia Qt LGPL Exception
       
    26 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
       
    27 **
       
    28 ** If you have questions regarding the use of this file, please contact
       
    29 ** Nokia at qt-info@nokia.com.
       
    30 **
       
    31 **
       
    32 **
       
    33 **
       
    34 **
       
    35 **
       
    36 **
       
    37 **
       
    38 ** $QT_END_LICENSE$
       
    39 **
       
    40 ****************************************************************************/
       
    41 
       
    42 #include <stdlib.h>
       
    43 #include <math.h>
       
    44 
       
    45 #include <QDebug>
       
    46 #include <QPainter>
       
    47 #include <QVBoxLayout>
       
    48 
       
    49 #include <qaudiodeviceinfo.h>
       
    50 #include <qaudioinput.h>
       
    51 
       
    52 #include <QtCore/qendian.h>
       
    53 
       
    54 #include "audioinput.h"
       
    55 
       
    56 const QString InputTest::PushModeLabel(tr("Enable push mode"));
       
    57 const QString InputTest::PullModeLabel(tr("Enable pull mode"));
       
    58 const QString InputTest::SuspendLabel(tr("Suspend recording"));
       
    59 const QString InputTest::ResumeLabel(tr("Resume recording"));
       
    60 
       
    61 const int BufferSize = 4096;
       
    62 
       
    63 AudioInfo::AudioInfo(const QAudioFormat &format, QObject *parent)
       
    64     :   QIODevice(parent)
       
    65     ,   m_format(format)
       
    66     ,   m_maxAmplitude(0)
       
    67     ,   m_level(0.0)
       
    68 
       
    69 {
       
    70     switch (m_format.sampleSize()) {
       
    71     case 8:
       
    72         switch (m_format.sampleType()) {
       
    73         case QAudioFormat::UnSignedInt:
       
    74             m_maxAmplitude = 255;
       
    75             break;
       
    76         case QAudioFormat::SignedInt:
       
    77             m_maxAmplitude = 127;
       
    78             break;
       
    79         default:
       
    80             break;
       
    81         }
       
    82         break;
       
    83     case 16:
       
    84         switch (m_format.sampleType()) {
       
    85         case QAudioFormat::UnSignedInt:
       
    86             m_maxAmplitude = 65535;
       
    87             break;
       
    88         case QAudioFormat::SignedInt:
       
    89             m_maxAmplitude = 32767;
       
    90             break;
       
    91         default:
       
    92             break;
       
    93         }
       
    94         break;
       
    95     default:
       
    96         break;
       
    97     }
       
    98 }
       
    99 
       
   100 AudioInfo::~AudioInfo()
       
   101 {
       
   102 }
       
   103 
       
   104 void AudioInfo::start()
       
   105 {
       
   106     open(QIODevice::WriteOnly);
       
   107 }
       
   108 
       
   109 void AudioInfo::stop()
       
   110 {
       
   111     close();
       
   112 }
       
   113 
       
   114 qint64 AudioInfo::readData(char *data, qint64 maxlen)
       
   115 {
       
   116     Q_UNUSED(data)
       
   117     Q_UNUSED(maxlen)
       
   118 
       
   119     return 0;
       
   120 }
       
   121 
       
   122 qint64 AudioInfo::writeData(const char *data, qint64 len)
       
   123 {
       
   124     if (m_maxAmplitude) {
       
   125         Q_ASSERT(m_format.sampleSize() % 8 == 0);
       
   126         const int channelBytes = m_format.sampleSize() / 8;
       
   127         const int sampleBytes = m_format.channels() * channelBytes;
       
   128         Q_ASSERT(len % sampleBytes == 0);
       
   129         const int numSamples = len / sampleBytes;
       
   130 
       
   131         quint16 maxValue = 0;
       
   132         const unsigned char *ptr = reinterpret_cast<const unsigned char *>(data);
       
   133 
       
   134         for (int i = 0; i < numSamples; ++i) {
       
   135             for(int j = 0; j < m_format.channels(); ++j) {
       
   136                 quint16 value = 0;
       
   137 
       
   138                 if (m_format.sampleSize() == 8 && m_format.sampleType() == QAudioFormat::UnSignedInt) {
       
   139                     value = *reinterpret_cast<const quint8*>(ptr);
       
   140                 } else if (m_format.sampleSize() == 8 && m_format.sampleType() == QAudioFormat::SignedInt) {
       
   141                     value = qAbs(*reinterpret_cast<const qint8*>(ptr));
       
   142                 } else if (m_format.sampleSize() == 16 && m_format.sampleType() == QAudioFormat::UnSignedInt) {
       
   143                     if (m_format.byteOrder() == QAudioFormat::LittleEndian)
       
   144                         value = qFromLittleEndian<quint16>(ptr);
       
   145                     else
       
   146                         value = qFromBigEndian<quint16>(ptr);
       
   147                 } else if (m_format.sampleSize() == 16 && m_format.sampleType() == QAudioFormat::SignedInt) {
       
   148                     if (m_format.byteOrder() == QAudioFormat::LittleEndian)
       
   149                         value = qAbs(qFromLittleEndian<qint16>(ptr));
       
   150                     else
       
   151                         value = qAbs(qFromBigEndian<qint16>(ptr));
       
   152                 }
       
   153 
       
   154                 maxValue = qMax(value, maxValue);
       
   155                 ptr += channelBytes;
       
   156             }
       
   157         }
       
   158 
       
   159         maxValue = qMin(maxValue, m_maxAmplitude);
       
   160         m_level = qreal(maxValue) / m_maxAmplitude;
       
   161     }
       
   162 
       
   163     emit update();
       
   164     return len;
       
   165 }
       
   166 
       
   167 RenderArea::RenderArea(QWidget *parent)
       
   168     : QWidget(parent)
       
   169 {
       
   170     setBackgroundRole(QPalette::Base);
       
   171     setAutoFillBackground(true);
       
   172 
       
   173     m_level = 0;
       
   174     setMinimumHeight(30);
       
   175     setMinimumWidth(200);
       
   176 }
       
   177 
       
   178 void RenderArea::paintEvent(QPaintEvent * /* event */)
       
   179 {
       
   180     QPainter painter(this);
       
   181 
       
   182     painter.setPen(Qt::black);
       
   183     painter.drawRect(QRect(painter.viewport().left()+10,
       
   184                            painter.viewport().top()+10,
       
   185                            painter.viewport().right()-20,
       
   186                            painter.viewport().bottom()-20));
       
   187     if (m_level == 0.0)
       
   188         return;
       
   189 
       
   190     painter.setPen(Qt::red);
       
   191 
       
   192     int pos = ((painter.viewport().right()-20)-(painter.viewport().left()+11))*m_level;
       
   193     for (int i = 0; i < 10; ++i) {
       
   194         int x1 = painter.viewport().left()+11;
       
   195         int y1 = painter.viewport().top()+10+i;
       
   196         int x2 = painter.viewport().left()+20+pos;
       
   197         int y2 = painter.viewport().top()+10+i;
       
   198         if (x2 < painter.viewport().left()+10)
       
   199             x2 = painter.viewport().left()+10;
       
   200 
       
   201         painter.drawLine(QPoint(x1, y1),QPoint(x2, y2));
       
   202     }
       
   203 }
       
   204 
       
   205 void RenderArea::setLevel(qreal value)
       
   206 {
       
   207     m_level = value;
       
   208     repaint();
       
   209 }
       
   210 
       
   211 
       
   212 InputTest::InputTest()
       
   213     :   m_canvas(0)
       
   214     ,   m_modeButton(0)
       
   215     ,   m_suspendResumeButton(0)
       
   216     ,   m_deviceBox(0)
       
   217     ,   m_device(QAudioDeviceInfo::defaultInputDevice())
       
   218     ,   m_audioInfo(0)
       
   219     ,   m_audioInput(0)
       
   220     ,   m_input(0)
       
   221     ,   m_pullMode(false)
       
   222     ,   m_buffer(BufferSize, 0)
       
   223 {
       
   224     initializeWindow();
       
   225     initializeAudio();
       
   226 }
       
   227 
       
   228 InputTest::~InputTest() {}
       
   229 
       
   230 void InputTest::initializeWindow()
       
   231 {
       
   232     QScopedPointer<QWidget> window(new QWidget);
       
   233     QScopedPointer<QVBoxLayout> layout(new QVBoxLayout);
       
   234 
       
   235     m_canvas = new RenderArea(this);
       
   236     layout->addWidget(m_canvas);
       
   237 
       
   238     m_deviceBox = new QComboBox(this);
       
   239     QList<QAudioDeviceInfo> devices = QAudioDeviceInfo::availableDevices(QAudio::AudioInput);
       
   240     for(int i = 0; i < devices.size(); ++i)
       
   241         m_deviceBox->addItem(devices.at(i).deviceName(), qVariantFromValue(devices.at(i)));
       
   242 
       
   243     connect(m_deviceBox, SIGNAL(activated(int)), SLOT(deviceChanged(int)));
       
   244     layout->addWidget(m_deviceBox);
       
   245 
       
   246     m_modeButton = new QPushButton(this);
       
   247     m_modeButton->setText(PushModeLabel);
       
   248     connect(m_modeButton, SIGNAL(clicked()), SLOT(toggleMode()));
       
   249     layout->addWidget(m_modeButton);
       
   250 
       
   251     m_suspendResumeButton = new QPushButton(this);
       
   252     m_suspendResumeButton->setText(SuspendLabel);
       
   253     connect(m_suspendResumeButton, SIGNAL(clicked()), SLOT(toggleSuspend()));
       
   254     layout->addWidget(m_suspendResumeButton);
       
   255 
       
   256     window->setLayout(layout.data());
       
   257     layout.take(); // ownership transferred
       
   258 
       
   259     setCentralWidget(window.data());
       
   260     QWidget *const windowPtr = window.take(); // ownership transferred
       
   261     windowPtr->show();
       
   262 }
       
   263 
       
   264 void InputTest::initializeAudio()
       
   265 {
       
   266     m_pullMode = true;
       
   267 
       
   268     m_format.setFrequency(8000);
       
   269     m_format.setChannels(1);
       
   270     m_format.setSampleSize(16);
       
   271     m_format.setSampleType(QAudioFormat::SignedInt);
       
   272     m_format.setByteOrder(QAudioFormat::LittleEndian);
       
   273     m_format.setCodec("audio/pcm");
       
   274 
       
   275     QAudioDeviceInfo info(QAudioDeviceInfo::defaultInputDevice());
       
   276     if (!info.isFormatSupported(m_format)) {
       
   277         qWarning() << "Default format not supported - trying to use nearest";
       
   278         m_format = info.nearestFormat(m_format);
       
   279     }
       
   280 
       
   281     m_audioInfo  = new AudioInfo(m_format, this);
       
   282     connect(m_audioInfo, SIGNAL(update()), SLOT(refreshDisplay()));
       
   283 
       
   284     createAudioInput();
       
   285 }
       
   286 
       
   287 void InputTest::createAudioInput()
       
   288 {
       
   289     m_audioInput = new QAudioInput(m_device, m_format, this);
       
   290     connect(m_audioInput, SIGNAL(notify()), SLOT(notified()));
       
   291     connect(m_audioInput, SIGNAL(stateChanged(QAudio::State)), SLOT(stateChanged(QAudio::State)));
       
   292     m_audioInfo->start();
       
   293     m_audioInput->start(m_audioInfo);
       
   294 }
       
   295 
       
   296 void InputTest::notified()
       
   297 {
       
   298     qWarning() << "bytesReady = " << m_audioInput->bytesReady()
       
   299                << ", " << "elapsedUSecs = " <<m_audioInput->elapsedUSecs()
       
   300                << ", " << "processedUSecs = "<<m_audioInput->processedUSecs();
       
   301 }
       
   302 
       
   303 void InputTest::readMore()
       
   304 {
       
   305     if(!m_audioInput)
       
   306         return;
       
   307     qint64 len = m_audioInput->bytesReady();
       
   308     if(len > 4096)
       
   309         len = 4096;
       
   310     qint64 l = m_input->read(m_buffer.data(), len);
       
   311     if(l > 0) {
       
   312         m_audioInfo->write(m_buffer.constData(), l);
       
   313     }
       
   314 }
       
   315 
       
   316 void InputTest::toggleMode()
       
   317 {
       
   318     // Change bewteen pull and push modes
       
   319     m_audioInput->stop();
       
   320 
       
   321     if (m_pullMode) {
       
   322         m_modeButton->setText(PullModeLabel);
       
   323         m_input = m_audioInput->start();
       
   324         connect(m_input, SIGNAL(readyRead()), SLOT(readMore()));
       
   325         m_pullMode = false;
       
   326     } else {
       
   327         m_modeButton->setText(PushModeLabel);
       
   328         m_pullMode = true;
       
   329         m_audioInput->start(m_audioInfo);
       
   330     }
       
   331 
       
   332     m_suspendResumeButton->setText(SuspendLabel);
       
   333 }
       
   334 
       
   335 void InputTest::toggleSuspend()
       
   336 {
       
   337     // toggle suspend/resume
       
   338     if(m_audioInput->state() == QAudio::SuspendedState) {
       
   339         qWarning() << "status: Suspended, resume()";
       
   340         m_audioInput->resume();
       
   341         m_suspendResumeButton->setText(SuspendLabel);
       
   342     } else if (m_audioInput->state() == QAudio::ActiveState) {
       
   343         qWarning() << "status: Active, suspend()";
       
   344         m_audioInput->suspend();
       
   345         m_suspendResumeButton->setText(ResumeLabel);
       
   346     } else if (m_audioInput->state() == QAudio::StoppedState) {
       
   347         qWarning() << "status: Stopped, resume()";
       
   348         m_audioInput->resume();
       
   349         m_suspendResumeButton->setText(SuspendLabel);
       
   350     } else if (m_audioInput->state() == QAudio::IdleState) {
       
   351         qWarning() << "status: IdleState";
       
   352     }
       
   353 }
       
   354 
       
   355 void InputTest::stateChanged(QAudio::State state)
       
   356 {
       
   357     qWarning() << "state = " << state;
       
   358 }
       
   359 
       
   360 void InputTest::refreshDisplay()
       
   361 {
       
   362     m_canvas->setLevel(m_audioInfo->level());
       
   363     m_canvas->repaint();
       
   364 }
       
   365 
       
   366 void InputTest::deviceChanged(int index)
       
   367 {
       
   368     m_audioInfo->stop();
       
   369     m_audioInput->stop();
       
   370     m_audioInput->disconnect(this);
       
   371     delete m_audioInput;
       
   372 
       
   373     m_device = m_deviceBox->itemData(index).value<QAudioDeviceInfo>();
       
   374     createAudioInput();
       
   375 }