问题
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:
Your application is missing a
QCoreApplication
if it is supposed to be headlessQGuiApplication
for QtQuick, orQApplication
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();
}
来源:https://stackoverflow.com/questions/55198955/qmediaplayer-doesnt-produce-audio