Evgenii Legotckoi
Sept. 23, 2015, 9 p.m.

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.


triangle.h

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

  1. #ifndef TRIANGLE_H
  2. #define TRIANGLE_H
  3.  
  4. #include <QObject>
  5. #include <QGraphicsItem>
  6. #include <QPainter>
  7. #include <QGraphicsScene>
  8. #include <QMediaPlayer>
  9. #include <QMediaPlaylist>
  10.  
  11. #include <windows.h>
  12.  
  13. class Triangle : public QObject, public QGraphicsItem
  14. {
  15. Q_OBJECT
  16. public:
  17. explicit Triangle(QObject *parent = 0);
  18. ~Triangle();
  19.  
  20. // The code from the previous lessons
  21.  
  22. QMediaPlayer * m_player; // Audio player
  23. QMediaPlaylist * m_playlist; // Playlist
  24.  
  25. };
  26.  
  27. #endif // TRIANGLE_H

triangle.cpp

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.

  1. #include "triangle.h"
  2.  
  3. Triangle::Triangle(QObject *parent) :
  4. QObject(parent), QGraphicsItem()
  5. {
  6. angle = 0;
  7. steps = 1;
  8. countForSteps = 0;
  9. setRotation(angle);
  10.  
  11. m_player = new QMediaPlayer(this); // Init player
  12. m_playlist = new QMediaPlaylist(m_player); // Init playlist
  13.  
  14. m_player->setPlaylist(m_playlist); // Set playlist into player
  15. m_playlist->addMedia(QUrl("qrc:/game/bzzz.wav")); // Adding of track to playlist
  16. m_playlist->setPlaybackMode(QMediaPlaylist::CurrentItemInLoop); // track loop
  17. }
  18.  
  19. Triangle::~Triangle()
  20. {
  21.  
  22. }
  23.  
  24. QRectF Triangle::boundingRect() const
  25. {
  26. return QRectF(-40,-50,80,100);
  27. }
  28.  
  29. void Triangle::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
  30. {
  31. // The code from the previous lessons
  32. }
  33.  
  34. void Triangle::slotGameTimer()
  35. {
  36. if(GetAsyncKeyState(VK_LEFT) ||
  37. GetAsyncKeyState(VK_RIGHT) ||
  38. GetAsyncKeyState(VK_UP) ||
  39. GetAsyncKeyState(VK_DOWN))
  40. {
  41. // The code from the previous lessons
  42.  
  43. m_player->play(); // The player plays only when the fly moves
  44. } else {
  45. m_player->stop();
  46. }
  47.  
  48. // The code from the previous lessons
  49. }

widget.h

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.

widget.cpp

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.

  1. #include "widget.h"
  2. #include "ui_widget.h"
  3.  
  4. Widget::Widget(QWidget *parent) :
  5. QWidget(parent),
  6. ui(new Ui::Widget)
  7. {
  8. // The code from the previous lessons
  9. }
  10.  
  11. Widget::~Widget()
  12. {
  13. delete ui;
  14. }
  15.  
  16. void Widget::slotDeleteApple(QGraphicsItem *item)
  17. {
  18. foreach (QGraphicsItem *apple, apples) {
  19. if(apple == item){
  20. scene->removeItem(apple);
  21. apples.removeOne(apple);
  22. delete apple;
  23. ui->lcdNumber->display(count++);
  24.  
  25. // The sound eating apple
  26. QMediaPlayer * m_player = new QMediaPlayer(this); // Initialize player
  27. QMediaPlaylist * m_playlist = new QMediaPlaylist(m_player); // create a playlist
  28.  
  29. m_player->setPlaylist(m_playlist); // set playlist to player
  30. m_playlist->addMedia(QUrl("qrc:/game/hrum.wav")); // Add audio to player
  31. m_playlist->setPlaybackMode(QMediaPlaylist::CurrentItemOnce); // play one time
  32. m_player->play(); // run player
  33. }
  34. }
  35. }
  36.  
  37. void Widget::slotCreateApple()
  38. {
  39. // The code from the previous lessons
  40. }
  41.  
  42. void Widget::on_pushButton_clicked()
  43. {
  44. // The code from the previous lessons
  45.  
  46. ui->pushButton->setEnabled(false);
  47.  
  48. gameState = GAME_STARTED;
  49. }
  50.  
  51. void Widget::slotGameOver()
  52. {
  53. timer->stop();
  54. timerCreateApple->stop();
  55.  
  56. // If Fly was Killed, then run death cry
  57. QMediaPlayer * m_player = new QMediaPlayer(this);
  58. QMediaPlaylist * m_playlist = new QMediaPlaylist(m_player);
  59.  
  60. m_player->setPlaylist(m_playlist);
  61. m_playlist->addMedia(QUrl("qrc:/game/scream.wav"));
  62. m_playlist->setPlaybackMode(QMediaPlaylist::CurrentItemOnce);
  63. m_player->play();
  64.  
  65. // The code from the previous lessons
  66. }
  67.  
  68. void Widget::slotPause()
  69. {
  70. // The code from the previous lessons
  71. }

Result

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:

Video

Do you like it? Share on social networks!

ВН
  • March 22, 2019, 5:08 p.m.
  • (edited)

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


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

Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • AK
    April 1, 2025, 11:41 a.m.
    Добрый день. В данный момент работаю над проектом, где необходимо выводить звук из программы в определенное аудиоустройство (колонки, наушники, виртуальный кабель и т.д). Пишу на Qt5.12.12 поско…
  • Evgenii Legotckoi
    March 9, 2025, 9:02 p.m.
    К сожалению, я этого подсказать не могу, поскольку у меня нет необходимости в обходе блокировок и т.д. Поэтому я и не задавался решением этой проблемы. Ну выглядит так, что вам действитель…
  • VP
    March 9, 2025, 4:14 p.m.
    Здравствуйте! Я устанавливал Qt6 из исходников а также Qt Creator по отдельности. Все компоненты, связанные с разработкой для Android, установлены. Кроме одного... Когда пытаюсь скомпилиров…
  • ИМ
    Nov. 22, 2024, 9:51 p.m.
    Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
  • Evgenii Legotckoi
    Oct. 31, 2024, 11:37 p.m.
    Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup