问题描述
我开始使用C ++,并且尝试使用Qt播放mp3文件.我写了这段代码,但是由于某种原因它无法正常工作.我已经搜索了互联网,但找不到能帮上忙的东西.
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.
这是我的代码:
#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:
这是我的.pro
文件:
TEMPLATE = app
TARGET = MediaPlayer
QT += core multimedia
SOURCES += main.cpp
环境:
我试图在Qt创建者和终端上运行此程序.
I tried to run this program on Qt creator and on terminal.
推荐答案
您的应用程序缺少
-
QCoreApplication
如果应该没有头 -
QGuiApplication
用于QtQuick,或 -
QApplication
(如果具有小部件)
QCoreApplication
if it is supposed to be headlessQGuiApplication
for QtQuick, orQApplication
if it features Widgets
Q*Application
是大多数Qt应用程序的必需组件,因为它是处理所有事件和主线程上的信号的部分.这就是为什么您会遇到与QTimer
相关的错误的原因,因为Qt无法事先用QThread
包装"主线程.
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.
只需添加它,以及app.exec();
即可启动它,就可以了. app.exec()
将阻止,直到您的应用程序完成.
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();
}
这篇关于QMediaPlayer不产生音频的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!