aviit aviit - 1 month ago 10
C++ Question

QMediaPlayer app not responding when play many times in a short duration

I created a default Qt GUI app, I added

void keyPressEvent(QKeyEvent* ev);
in the mainwindow class, when user presses the space, the app will plays the sound (ok) but when the user press many times in a short duration, the app will not respond. I don't know why? Help me, please!

.pro file:

QT += core gui multimedia

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

TARGET = untitled2
TEMPLATE = app


SOURCES += main.cpp\
mainwindow.cpp

HEADERS += mainwindow.h

FORMS += mainwindow.ui

RESOURCES += \
res.qrc


mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QMediaPlayer>

namespace Ui { class MainWindow; }

class MainWindow : public QMainWindow {
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
void keyPressEvent(QKeyEvent* ev);
private:
Ui::MainWindow *ui;
QMediaPlayer mp;
};

#endif // MAINWINDOW_H


mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QKeyEvent>

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow)
{ ui->setupUi(this); }

MainWindow::~MainWindow() { delete ui; }

void MainWindow::keyPressEvent(QKeyEvent* ev) {
switch(ev->key()) {
case Qt::Key_Space: {
mp.setMedia(QUrl("qrc:/sounds/Fireworks.wav"));
mp.play();
break;
}
}
}


main.cpp

#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}


(Note: I did upload mainwindow.ui. res.qrc here)

Answer

mp.setMedia(QUrl("qrc:/sounds/Fireworks.wav"));

Do not set the media unnecessarily, as the mediaplayer doesnt check internally "Oh the media is the same I am going to be clever"

Rather you want to start the media from the beginning when its key is pressed again. The simplest solution is to have a boolean which indicate if the media is set.

  case Qt::Key_Space: 
  {
    if(!is_media_set)
    {
        mp.setMedia(QUrl("qrc:/sounds/Fireworks.wav"));
        is_media_set = true;
    }
    mp.setPosition(0);
    mp.play();
    break;
  }

If several keys trigger different sounds replace the boolean with current_media_key to indicate the last media loaded.