How to make game using Qt - Lesson 5. Adding sound QMediaPlayer

Getting to the fifth and final lesson on writing games on Qt, which will add sound using QMediaPlayer class. I propose to add the three types of sounds: Eating apples, buzzing flies that will be buzzing when moving and heartbreaking cry when Fly will eaten.

The sound in the project structure

The sound in the project structure is placed in a resource file, as shown in the screenshot of the project structure.

To do this, create a resource directory and folder game . Further, in the resources folder, create a resource file, which prescribes the prefix "/" and add audio files that are pre-placed in the game folder.

And then the sound must be connected to the project using QMediaPlayer class.

In this case, the sounds are connected in three places of the code.


In the header file, you must connect the class library and QMediaPlayer QMediaPlaylist. And also announce at the object of these classes.

#ifndef TRIANGLE_H
#define TRIANGLE_H

#include <QObject>
#include <QGraphicsItem>
#include <QPainter>
#include <QGraphicsScene>
#include <QMediaPlayer>
#include <QMediaPlaylist>

#include <windows.h>

class Triangle : public QObject, public QGraphicsItem
    explicit Triangle(QObject *parent = 0);

    // The code from the previous lessons

    QMediaPlayer * m_player;        // Audio player
    QMediaPlaylist * m_playlist;    // Playlist


#endif // TRIANGLE_H


Initialization QMediaPlayer object is made in the constructor of the class, but the management of audio playback will be realized in the slot game Fly as fly should buzz only when the game moves on stage.

#include "triangle.h"

Triangle::Triangle(QObject *parent) :
    QObject(parent), QGraphicsItem()
    angle = 0;     
    steps = 1;      
    countForSteps = 0;     

    m_player = new QMediaPlayer(this);          // Init player
    m_playlist = new QMediaPlaylist(m_player);  // Init playlist

    m_player->setPlaylist(m_playlist);          // Set playlist into player
    m_playlist->addMedia(QUrl("qrc:/game/bzzz.wav"));       // Adding of track to playlist
    m_playlist->setPlaybackMode(QMediaPlaylist::CurrentItemInLoop); // track loop



QRectF Triangle::boundingRect() const
    return QRectF(-40,-50,80,100);   

void Triangle::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
   // The code from the previous lessons

void Triangle::slotGameTimer()
    if(GetAsyncKeyState(VK_LEFT) ||
       GetAsyncKeyState(VK_RIGHT) ||
       GetAsyncKeyState(VK_UP) ||
       // The code from the previous lessons

        m_player->play();   // The player plays only when the fly moves
    } else {

    // The code from the previous lessons


The class header file, which acts as the core of the game, you only need to connect the library, which are responsible for classes and QMediaPlayer QMediaPlaylist.


In this class, there is no global ad QMediaPlayer object because objects are created dynamically, for example, for every apple eaten. Due to the fact that apples can be eaten very quickly and almost simultaneously, and the sounds of eating apples will sound together, one player can not cope with such a task, so you have to run on the player at every sound. Also individual player will play death of Fly.

#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent) :
    ui(new Ui::Widget)
    // The code from the previous lessons

    delete ui;

void Widget::slotDeleteApple(QGraphicsItem *item)
    foreach (QGraphicsItem *apple, apples) {
        if(apple == item){
            delete apple;               

            // The sound eating apple
            QMediaPlayer * m_player = new QMediaPlayer(this);   // Initialize player
            QMediaPlaylist * m_playlist = new QMediaPlaylist(m_player); // create a playlist

            m_player->setPlaylist(m_playlist);  // set playlist to player
            m_playlist->addMedia(QUrl("qrc:/game/hrum.wav")); // Add audio to player
            m_playlist->setPlaybackMode(QMediaPlaylist::CurrentItemOnce); // play one time
            m_player->play();   // run player

void Widget::slotCreateApple()
   // The code from the previous lessons

void Widget::on_pushButton_clicked()
   // The code from the previous lessons


    gameState = GAME_STARTED;

void Widget::slotGameOver()

    // If Fly was Killed, then run death cry
    QMediaPlayer * m_player = new QMediaPlayer(this);       
    QMediaPlaylist * m_playlist = new QMediaPlaylist(m_player); 


    // The code from the previous lessons

void Widget::slotPause()
    // The code from the previous lessons


That's finished work on our first game. Now you have an idea of how to create a simple game on the Qt C ++.

Full source code: Source

Game: Muha_Setup

A full list of articles in this series:


We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.
Support the author Donate

Из кьюта приложение не хочет запускаться, аварийно завершается, но каких-либо ошибок не выдаёт. Оно открывается, после нажатия "старт" зависает и завершается. Если не из кьюта запускать дебаг - та же ерунда. Релиз вообще отказывается работать, ошибки на картинках. Все dll и libs доложила и в дебаг, и в релиз. В чём может быть проблема? А windeployqt вообще динамит, открывает консоль на секунду - и всё. Удаление qmakes и pro.user тоже не помогает

Ну может бибилотеки не те положили? У вас сборка для MinGW, а либы для MSVC.


Only authorized users can post comments.
Please, Log in or Sign up
How to become an author?

Contribute to the evolution of the EVILEG community.

Learn how to become a site author.

Learn it

Good day, Dear Users!!!

I am Evgenii Legotckoi, developer of EVILEG. And it is my hobby project, which helps to learn programming another programmers and developers

If the site helped you, and you want also support the development of the site, than you can donate by following ways


Let me recommend you the excellent hosting on which EVILEG is located.

For many years, Timeweb has been proving his stability.

For projects on Django I recommend VDS hosting

View Hosting Timeweb
June 5, 2020, 2:28 a.m.

Qt - Test 001. Signals and slots

  • Result:0points,
  • Rating points-10
June 3, 2020, 1:56 a.m.

C++ - Тест 003. Условия и циклы

  • Result:35points,
  • Rating points-10
June 2, 2020, 9:11 p.m.
Aleksej Pikenin

C++ - Test 005. Structures and Classes

  • Result:75points,
  • Rating points2
Last comments
June 5, 2020, 1:39 a.m.
Evgenij Legotskoj

Qt/C++ - Tutorial 091. How to write a custom delegate controlling the highlighting of a row in a table

По-моему, смысла в этом нет особого. Если делегат будет игнорировать настройки таблицы, то это приведёт ещё к большему непониманию, что вообще происходит, для программиста, который после вас буд…
June 5, 2020, 1:34 a.m.

Qt/C++ - Tutorial 091. How to write a custom delegate controlling the highlighting of a row in a table

Сижу, размышляю: можно ли переписать делегата так, чтобы независимо от настроек строк выделялись строки?
June 5, 2020, 1:31 a.m.
Evgenij Legotskoj

Qt/C++ - Tutorial 091. How to write a custom delegate controlling the highlighting of a row in a table

Понятно. Я не обратил внимания на то, что там было в старом коде по настройкам строк :)
June 5, 2020, 1:27 a.m.

Qt/C++ - Tutorial 091. How to write a custom delegate controlling the highlighting of a row in a table

Разобрался. У вас изначально в проекте были вот эти настройки: ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows);ui->tableView->setSelectionMode(QAbstractItemVie…
June 4, 2020, 11:10 a.m.

Qt/C++ - Tutorial 091. How to write a custom delegate controlling the highlighting of a row in a table

Полностью скопировал пример - всё правильно работает. Значит, где-то у меня ошибки в тестовом проекте. Буду разбираться. Извините за беспокойство. :)
Now discuss on the forum
June 5, 2020, 6:13 a.m.

Фильтр для QtableView sql

Добрый день. Для такой фильтрации необходимо использовать QSortFilterProxyModel. В оффдоках есть хороший пример.
June 4, 2020, 2:46 a.m.
Mihail A

Qt- C++ QTableView подсветить строку

June 3, 2020, 1:49 a.m.

Можно ли сделать в QML таблицу как в Excel?

edi-tableview - нашел пока такое выглядит коряво, посмотрим что можно сделать
June 2, 2020, 2:46 a.m.
Evgenij Legotskoj

Медиа файлы Google Firebase

Картинки можете попробовать сжимать через QPixmap, там есть возможность установки scaleFactor, через него можете устанавливать нужные параметры. А что касается конвертации видео, то лучше п…
June 2, 2020, 2:01 a.m.
Evgenij Legotskoj

Перехват обращения к локальным файлам QWebEngineView

В вашем случае вполне адекватное решение. Так сказать меньше зло. В противном случае пришлось бы очень много переписывать и перепиливать.
© EVILEG 2015-2020
Recommend hosting TIMEWEB