QMediaPlayer不产生音频 [英] QMediaPlayer doesn't produce audio

查看:294
本文介绍了QMediaPlayer不产生音频的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始使用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:

QObject :: startTimer:计时器只能与以QThread启动的线程一起使用
QObject :: startTimer:计时器只能与以QThread开头的线程一起使用

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

这是我的.pro文件:

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

环境:

Fedora 29
Qt 5.11.3-1

Fedora 29
Qt 5.11.3-1

我试图在Qt创建者和终端上运行此程序.

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

推荐答案

您的应用程序缺少

  • QCoreApplication如果应该没有头
  • QGuiApplication用于QtQuick,或
  • QApplication(如果具有小部件)
  • QCoreApplication if it is supposed to be headless
  • QGuiApplication for QtQuick, or
  • QApplication 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不产生音频的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆