Qt/C++ - Lesson 051. QMediaPlayer – simple audio player

QMediaPlayer, QMediaPlaylist, QStandardItemModel, Qt, аудио плеер

I suggest to write a simple audio player for mp3 files using Qt/C++, which will have a playlist, the ability to start / pause / stop tracks, as well as scroll through the tracks.

For the implementation of this ideas in Qt, classes are QMediaPlayer and QMediaPlaylist, which belong to the multimedia module. And to display the playlist and use QStandardItemModel QTableView.

Articles in this series:

Project structure

  • SimplePlayer.pro - the profile of the project;
  • main.cpp - the file with the main function;
  • widget.ui - form of application window;
  • widget.h - header file of the application window;
  • widget.cpp - file source code of the application window;
  • buttons.qrc - resource file application icon buttons.

widget.ui

The application interface is made using a graphic designer, and it have look as follows.

The application interface consists of the following elements:

  • btn_add (QToolButton*) - responsible for adding tracks to the playlist;
  • btn_next (QToolButton*) - responsible for flipping the playlist ahead;
  • btn_previous (QToolButton*) - responsible for flipping playlist ago;
  • btn_play (QToolButton*) - responsible for track playback;
  • btn_pause (QToolButton*) - responsible for setting the track is paused;
  • btn_stop (QToolButton*) - responsible for track stop;
  • currentTrack (QLabel*) - label, which will display the current track;
  • playlistView (QTableView*) - table, which displays the playlist.

SimplePlayer.pro

The project profile that you connect the multimedia module, otherwise QMediaPlayer and QMediaPlaylist classes will be not available.

#-------------------------------------------------
#
# Project created by QtCreator 2016-06-29T11:25:56
#
#-------------------------------------------------

QT       += core gui multimedia

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

TARGET = SimplePlayer
TEMPLATE = app


SOURCES += main.cpp\
        widget.cpp

HEADERS  += widget.h

FORMS    += widget.ui

RESOURCES += \
    buttons.qrc

widget.h

To implement the playlist display, have to use QStandardItemModel. In it will be placed in the path of audio files and audio file names. The first column is the name of the audio file, and the second will be the full path, but this column will be hidden in a QTableView object, which will be responsible for mapping Playlist.

Also, the path to the file as a media source will need to be put in QMediaPlaylist object that will be placed in QMediaPlayer.

Pointers to these objects are placed in the header file of the application window. Also here there avtogenerirovany through designer interface slot to press the button add tracks to the playlist processing.

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include <QStandardItemModel>
#include <QMediaPlayer>
#include <QMediaPlaylist>

namespace Ui {
class Widget;
}

class Widget : public QWidget
{
    Q_OBJECT

public:
    explicit Widget(QWidget *parent = 0);
    ~Widget();

private slots:
    void on_btn_add_clicked();              // The slot for the processing of adding tracks through dialog

private:
    Ui::Widget *ui;
    QStandardItemModel  *m_playListModel;   // Data Model for Playlist
    QMediaPlayer        *m_player;          
    QMediaPlaylist      *m_playlist;       
};

#endif // WIDGET_H

widget.cpp

For realization of the player it is necessary to initialize the object QMediaPlayer , QMediaPlaylist and QStandardItemModel , which have been declared in the header file of the application window. In the first half of the designer made customize the appearance of the table to display the playlist, while the second setting of the player. player controlled via the buttons that are connected to the control slots m_playlist (for navigation) and m_player (to start / pause / stop).

If you change the current track, the player will automatically terminates playback of the track that was before the change, and starts to play a new track.

Due to the fact that QMediaPlaylist has no model to be displayed in the table, we use the QStandardItemModel class, so you have to add data about file paths and there and there.

#include "widget.h"
#include "ui_widget.h"
#include <QFileDialog>
#include <QDir>

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    m_playListModel = new QStandardItemModel(this);
    ui->playlistView->setModel(m_playListModel);    
    m_playListModel->setHorizontalHeaderLabels(QStringList()  << tr("Audio Track")
                                                            << tr("File Path"));
    ui->playlistView->hideColumn(1);   
    ui->playlistView->verticalHeader()->setVisible(false);                  
    ui->playlistView->setSelectionBehavior(QAbstractItemView::SelectRows);  
    ui->playlistView->setSelectionMode(QAbstractItemView::SingleSelection); 
    ui->playlistView->setEditTriggers(QAbstractItemView::NoEditTriggers);  
    ui->playlistView->horizontalHeader()->setStretchLastSection(true);

    m_player = new QMediaPlayer(this);          // Init player
    m_playlist = new QMediaPlaylist(m_player);  // Init playlist
    m_player->setPlaylist(m_playlist);          
    m_player->setVolume(70);                    
    m_playlist->setPlaybackMode(QMediaPlaylist::Loop);  // Set circular play mode playlist

    // подключаем кнопки управления к слотам управления
    // Here we note that the navigation is done through the playlist playlist
    // and start / pause / stop via the player itself
    connect(ui->btn_previous, &QToolButton::clicked, m_playlist, &QMediaPlaylist::previous);
    connect(ui->btn_next, &QToolButton::clicked, m_playlist, &QMediaPlaylist::next);
    connect(ui->btn_play, &QToolButton::clicked, m_player, &QMediaPlayer::play);
    connect(ui->btn_pause, &QToolButton::clicked, m_player, &QMediaPlayer::pause);
    connect(ui->btn_stop, &QToolButton::clicked, m_player, &QMediaPlayer::stop);

    // When you doubleclick on the track in the table set the track in the playlist
    connect(ui->playlistView, &QTableView::doubleClicked, [this](const QModelIndex &index){
        m_playlist->setCurrentIndex(index.row());
    });

    // if the current track of the index change in the playlist, set the file name in a special label
    connect(m_playlist, &QMediaPlaylist::currentIndexChanged, [this](int index){
        ui->currentTrack->setText(m_playListModel->data(m_playListModel->index(index, 0)).toString());
    });
}

Widget::~Widget()
{
    delete ui;
    delete m_playListModel;
    delete m_playlist;
    delete m_player;
}

void Widget::on_btn_add_clicked()
{
    // Using the file selection dialog to make multiple selections of mp3 files
    QStringList files = QFileDialog::getOpenFileNames(this,
                                                      tr("Open files"),
                                                      QString(),
                                                      tr("Audio Files (*.mp3)"));

    // Next, set the data names and file paths
    // into the playlist and table displaying the playlist
    foreach (QString filePath, files) {
        QList<QStandardItem *> items;
        items.append(new QStandardItem(QDir(filePath).dirName()));
        items.append(new QStandardItem(filePath));
        m_playListModel->appendRow(items);
        m_playlist->addMedia(QUrl(filePath));
    }
}

Result

Once the app is started, you can open the mp3 tracks and listen to them.

Download Qt Audio Player

Video

10% refund of hotel reservation amount on Booking
10% refund of hotel reservation amount on Booking
We offer a link with a 10% return on the amount of the order when booking a hotel through Booking
Support the author Donate
S

Скажите, пожалуйста, как на линуксе исправить ошибку , связанную с непраильной схемой пути к файлу - "Error: "Invalid URI ...."" и далее соответственно GSteamer; unable to pause...

На официальном форуме указано на то, что "when passing local file to the media player, you need to use the "file://" scheme so it knows it has to look in to the file system." Но что конкретно из этого стоит вынести, не ясно.
Благодарен за внимание.

Ответил на форуме

Comments

Only authorized users can post comments.
Please, Log in or Sign up
TT
June 13, 2019, 7:01 p.m.
Taimoor Tanweer

C++ - Test 001. The first program and data types

  • Result:66points,
  • Rating points-1
TT
June 13, 2019, 6:51 p.m.
Taimoor Tanweer

C++ - Test 002. Constants

  • Result:75points,
  • Rating points2
ВМ
June 13, 2019, 12:30 p.m.
Ваня Мороз

C++ - Test 001. The first program and data types

  • Result:100points,
  • Rating points10
Last comments
i
June 17, 2019, 6:10 a.m.
ingenfly

Только по осям xAxis2, уAxis2 значения начинаются с 0. Почему-то xAxis2 и xAxis не синхронизированы по данным. Ну и QCustomPlot последний.
June 16, 2019, 8:21 p.m.
Евгений Легоцкой

Добрый день. Ну точно также добавляете ту же самую информацию на ось xAxis2, только добавляете другое форматирование customPlot->xAxis2->setDateTimeFormat("hh:mm"); если я ...
EF
June 14, 2019, 1:56 p.m.
Egor Fomin

Спасибо за ваш ответ, у меня получилось реализовать это. Тем не менее появилась другая проблема, поэтому опять надеюсь на вашу помощь. Скажем, я уже выставил точки и они соеденены. Когда я нач...
d
June 13, 2019, 2:47 p.m.
damix

Можно классу, который описывает точку, добавить сигнал, который подавать (emit), когда точка перемещается (переопределить mouseMoveEvent или mouseReleaseEvent). Так вот эти сигналы у каждой из...
i
June 13, 2019, 2:09 p.m.
ingenfly

Здравствайте! Подскажите, пожалуйста: customPlot->xAxis2->setTickLabels(true); //Здесь включается отображение данных на оси xAxis2. а можно как-то продублировать информацию cus...
Now discuss on the forum
June 20, 2019, 9:30 a.m.
IscanderChe

Вернулся к этой задачке только-только, поэтому и не ответил ничего раньше.Как переопределить mouseReleaseEvent(QMouseEvent* event) у QTableView, если QTableView задан в ui? Или задавать QTabl...
I
June 19, 2019, 1:41 p.m.
Intruder

Всем добрый день. При разборе XML файла наткнулся на тег вот такого плана: <TagName attribute1="value1" attribute2="value2" /> При попытке проверить на наличие такого элеме...
June 19, 2019, 12:55 p.m.
Михаиллл

Скажите пожалуйста, как его в таком случае перемещать и удалять?
June 18, 2019, 7:50 p.m.
Дмитрий

Большое спасибо! SDK заработал.К сожалению удалось продвинутся только на один шаг. При сборке чистого проекта NDK выдаёт следующие ошибки C:\Android\ndk-bundle/toolchains/arm-linux-andr...
June 18, 2019, 4:59 p.m.
Михаиллл

Добрый день.В этом учебнике представлен код INSTALLED_APPS = ( ... 'rest_framework', 'snippets.apps.SnippetsConfig',) На строчке 'snippets.apps.SnippetsConf...
Looking for a Job?
25,000.00 руб. - 30,000.00 руб.
Разработчик Qt/C++
Barnaul, Altai Krai, Russia

For registered users on the site there is a minimum amount of advertising

EVILEG
About
Services
Join us
© EVILEG 2015-2019
Recommend hosting TIMEWEB