English Български

Play Audio File Using Qt Mobility

Overview

This article shows how to play audio file using QMediaPlayer [doc.qt.nokia.com] from Qt Mobility 1.1.

Project Configuration

Modify the project configuration .pro file by including Qt Mobility support:

  1. CONFIG += mobility
  2. MOBILITY += multimedia

Source Code

  • .h

Include required headers:

  1. #include <QMediaPlayer>

Declare slot and private members:

  1. private slots:
  2.     void statusChanged(QMediaPlayer::MediaStatus status);
  3.  
  4. private:
  5.  
  6.     QMediaPlayer *m_pPlayer;

  • .cpp

Play a file located on the device:

  1. m_pPlayer = new QMediaPlayer(this);
  2. connect(m_pPlayer, SIGNAL(positionChanged(qint64)), this, SLOT(statusChanged(qint64)));
  3. //Select a file
  4. m_pPlayer->setMedia(QUrl::fromLocalFile("e:\\Sounds\\Digital\\Girl_Rules.mp3"));
  5. //Set the volume
  6. m_pPlayer->setVolume(50);
  7. m_pPlayer->play();

Implement the declared slot:

  1. void MainWindow::statusChanged(QMediaPlayer::MediaStatus status)
  2. {
  3.     if ( (QMediaPlayer::LoadedMedia == status) && m_pPlayer)
  4.     {
  5.         m_pPlayer->play();
  6.     }
  7. }

Categories: