简体   繁体   中英

Referring to a predefined QMediaPlayer

Hi I am still learning C++ and QT for my major project for school this year and I would like some help with some syntax of C++ and using certain QT functions. As I am making a media manager, I have managed to get a song to play from pressing a button from a form. Now I want to pause the same song by pressing another button, but I am not completely sure what to do, could you help?

I already have this to play a song:

void MainWindow::playAudioFile(){
    QMediaPlayer *player = new QMediaPlayer(this);
    player->setMedia(QUrl::fromLocalFile("LOCATION OF SONG FILE"));
    player->setVolume(50);
    player->play();
}   

But I want to know how to pause the same audioi file from the QMediaPlayer called 'player', and at the moment all I have thought of is this and I am not sure if I am doing it correctly:

void MainWindow::pauseAudioFile(){
    player->pause();
}

Both of these functions (if that is what they are called) begin with a button press, which I know works for the first one.

You are trying to access a non-accessible object here:

void MainWindow::pauseAudioFile(){
    player->pause();
}

I am surprised if it was even compiling for you. The solution would be to change this:

QMediaPlayer *player = new QMediaPlayer(this);

to

player = new QMediaPlayer(this);

where the "player" object is the member of your MainWindow class, so basically you would put this into your MainWindow class:

#include <QMainWindow>
#include <QMediaPlayer>

class MainWindow : public QMainWindow
{
    Q_OBJECT
    public:
        explicit MainWindow(QObject *parent = 0)
            : QObject(parent)
            , player(new MediaPlayer(this))
    ...
    public slots:
        void playAudioFile() {
            player->setMedia(QUrl::fromLocalFile("LOCATION OF SONG FILE"));
            player->setVolume(50);
            player->play();
        }
        void pauseAudioFile(){
            player->pause();
        }
    private:
        QMediaPlayer *player;
}

That being said, you may not need a heap object in this case at all, and you can start using a stack object without dynamic memory allocation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM