【问题标题】:Qt QMediaPlayer works only from mainQt QMediaPlayer 仅适用于 main
【发布时间】:2018-05-14 16:03:26
【问题描述】:

我在 QT 中构建了一个简单的媒体播放器, 这是代码:

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();

   QMediaPlayer* player = new QMediaPlayer;
   QVideoWidget *vw = new QVideoWidget;

   player->setVideoOutput(vw);
   w.setCentralWidget(vw);

   QFile io("C:\\file.mp4");
   io.open(QFile::ReadOnly);

   player->setMedia(QUrl::fromLocalFile("C:\\file.mp4"), &io);

   vw->show();
   player->play();

   return a.exec();

}

当我尝试运行 MAIN.CPP 文件中的代码时,它可以工作并且一切正常。

当我尝试从文件 MAINWINDOW.CPP 运行它时,它不起作用(即使代码是相同的,除了这一行 -

player = new QMediaPlayer(this);
vw= new QVideoWidget(this);

this->setCentralWidget(vw);

playervw 现在在MAINWINDOW.h)

为什么会这样?

【问题讨论】:

  • 可能你的QFile 超出范围 - 试试QFile *io = new QFile("C:\\file.mp4", this);

标签: c++ windows qt qt5


【解决方案1】:

根据文档:

如果提供了流;将从中读取媒体数据,而不是 解析媒体源。在这种情况下,媒体源可能仍然是 用于解析有关媒体的附加信息,例如 mime 类型。流必须是开放且可读的。

在您的情况下,流的源是 QFile,但这是一个局部变量,将在构造函数完成运行时被删除。解决方案是在堆中创建它

QFile *io = new QFile("C:\\file.mp4", this);
if(io->open(QFile::ReadOnly))
    player->setMedia(QUrl::fromLocalFile("C:\\file.mp4"), io);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多