QMediaPlayer::setMedia()
从文档异步执行加载:
此函数在录制指定的媒体源后立即返回。它不等待媒体完成加载,也不检查错误。当媒体加载和加载过程中发生错误时,监听mediaStatusChanged()
和信号。error()
这意味着立即调用后QMediaPlayer
查询可能不起作用,因为可能尚未加载媒体。duration()
setMedia()
QMediaPlayer
为了保证调用前加载完成duration()
,必须监听mediaStatusChanged()
信号,返回duration()
时获取。这是一个最小的例子:mediaStatus()
QMediaPlayer::LoadedMedia
#include <QtWidgets>
#include <QtMultimedia>
int main(int argc, char* argv[])
{
QApplication app(argc, argv);
QLabel label; //a label to display duration
QString fileName = QFileDialog::getOpenFileName(nullptr, "Open Media File");
QMediaPlayer mp;
mp.setMedia(QUrl::fromLocalFile(fileName));
QObject::connect(&mp, &QMediaPlayer::mediaStatusChanged,
[&](QMediaPlayer::MediaStatus status){
if(status == QMediaPlayer::LoadedMedia) //when loading is finished
{
//show duration in a label
qint64 duration= mp.duration();
label.setText(QString("Duration: %1 ms.\n\nThat is: %2")
.arg(duration)
.arg(QDateTime::fromTime_t(duration/1000).toUTC()
.toString("hh:mm:ss")));
label.show();
}
});
return app.exec();
}