QT QMediaplayer 的duration()函數獲取不到正確時間的問題

QT關於QMediaplayer 的duration()獲取的音視頻時間長度爲0的問題。

  在QT中,使用QMediaplayer類可以很方便地實現視頻的播放,而在QMediaplayer類中有個duration函數可以直接獲取所打開視頻的總時間長度。但使用後你會發現duration()返回的居然是個0。
  認真看過幫助文檔你就會發現其實幫助文檔已經說明了這個問題的解決方法:
The value may change across the life time of the QMediaPlayer object and may not be available when initial playback begins, connect to the durationChanged() signal to receive status notifications.
在初始回放開始時可能不可用,請連接durationChanged()信號以接收狀態通知。
即我們只需要寫個槽函數,在槽函數裏面調用duration()就可以接收到正確的時間
例:

//第一步:連接槽函數,信號爲QMediaPlayer自帶的durationChanged,槽就是自己定義的getduration,注意參數類型要一致
QObject::connect(player,
				  SIGNAL(durationChanged(qint64)),
				  this,
				  SLOT(getduration(qint64)));

//第二步:寫槽函數,mediaplay爲類名,不同類需要修改這個類名,playtime爲總時長
void mediaplay::getduration(qint64 playtime)
{
    playtime = player->duration();
}

經過以上兩步就可以獲得正確的時間啦。

以下再附上把獲得的時間轉化爲時分秒的函數,希望對你有用

void settime(qint64 playtime)
{
	int h,m,s;
	playtime /= 1000;  //獲得的時間是以毫秒爲單位的
	h = playtime/3600;
	m = (playtime-h*3600)/60;
	s = playtime-h*3600-m*60;
	ui->label_time->setText(QString("%1:%2:%3").arg(h).arg(m).arg(s));  //把int型轉化爲string類型後再設置爲label的text
	ui->label_time->setStyleSheet("color:white");  //設置字體顏色爲白色
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章