QMediaPlayer doesn't produce audio

2020-05-06 10:22发布

I am starting out in C++ and I am trying to play an mp3 file with Qt. I wrote this code but it is not working for some reason. I have searched the internet but was unable to find something that would help.

Here's my code:

#include <iostream>
#include <QMediaPlayer>
#include <QMediaPlaylist>
#include <QFileInfo>
#include <QUrl>

int main()
{
    QMediaPlaylist *list = new QMediaPlaylist;
    list->addMedia(QUrl::fromLocalFile(QFileInfo("Filename.mp3").absoluteFilePath()));
    QMediaPlayer *music;
    music = new QMediaPlayer();
    music->setPlaylist(list);
    music->play();
    return 0;
}

There is no music playing and the output of this program is:

QObject::startTimer: Timers can only be used with threads started with QThread
QObject::startTimer: Timers can only be used with threads started with QThread

Here's my .pro file:

TEMPLATE = app
TARGET = MediaPlayer
QT += core multimedia
SOURCES += main.cpp

Environment:

Fedora 29
Qt 5.11.3-1

I tried to run this program on Qt creator and on terminal.

1条回答
相关推荐>>
2楼-- · 2020-05-06 11:09

Your application is missing a

  • QCoreApplication if it is supposed to be headless
  • QGuiApplication for QtQuick, or
  • QApplication if it features Widgets

Q*Application is a mandatory component for most Qt applications, as this is the piece that processes all events and signal on the main thread. This is the reason why you are having QTimer related errors, as Qt was not able to "wrap" the main thread with a QThread beforehand.

Just add it, as well as app.exec(); to start it, and you should be fine. app.exec() will block until your application finishes.

Also, instances that you need during the whole lifetime of the application should usually be created on the stack, instead of the heap.

int main(int argc, char *argv[]) {
    QCoreApplication app(argc, argv);

    QMediaPlaylist list;
    auto media = QUrl::fromLocalFile(QFileInfo("Filename.mp3").absoluteFilePath());
    list.addMedia(media);

    QMediaPlayer music;
    music.setPlaylist(list);
    music.play();

    return app.exec();
}
查看更多
登录 后发表回答