QMediaPlayer+QVideoWidget+QAudioOutput實現一個簡單視頻播放器-Qt6.8
此篇是我在觀看使用nginx搭建音視頻點播服務器 - seedoubleu - 博客園后,想著使用qt widget寫的一個簡單播放器
完成nginx搭建音視頻點播服務器的話,我推薦使用ffplay進行驗證.再推薦一個視頻【音視頻】FFmpeg音視頻入門到精通+實戰課_嗶哩嗶哩_bilibili
同時推薦一個好用的視頻下載工具(支持bilibili視頻下載)KurtBestor/Hitomi-Downloader: ?? Desktop utility to download images/videos/music/text from various websites, and more.
下圖是最終寫出來的界面(一共就倆界面文件,一個是displayVideo播放視頻窗口,一個是videocontrolbar的視頻控制欄(詳細代碼查看my_learnt/DisplayVideo at main · haoyouxiaoju/my_learnt)
- 如果有其他不懂的地方可以私信我,看到的話會回復

其中controlbar簡單的使用designer拖拽出來!

這里只寫一些注意事項:
我使用的是qt6.8 同時項目也是cmake項目
- 在使用qrc管理資源時,你可能會發現QFile沒法找到qrc管理的文件這時候你得在cmakeLists.txt中查看
# 啟用 Qt 資源支持
set(CMAKE_AUTORCC ON) # 必須開啟(否則qrc文件無法參與編譯)
- QVideoWidget是一個特殊的渲染widget,需要設置一下鼠標穿透
setAttribute(Qt::WA_TransparentForMouseEvents, true);
- 同時使用過程中發現視頻開頭會黑屏
//寫這個的原因是以為視頻開頭會黑屏,如果直接設置player的position為0不能解決
//通過嘗試,設置105剛剛好
//可能跟視頻的關鍵幀有關吧
QTimer* timer = new QTimer;
connect(timer, &QTimer::timeout, [=]() {
qDebug() << "Media status:" << player->mediaStatus();
qDebug() << "是否支持seek:" << player->isSeekable(); // 此時再檢查
if (player->isSeekable() == true) {
player->setPosition(105);
qDebug() << "durantion" << player->duration();
timer->stop();
timer->deleteLater();
}
});
timer->start(1000); // 每 100ms 檢查一次
- 這里的話是因為v_widget和controlBar沒有掛靠在DisplayVideo,是popup所以在移動和resize DisplayVideo的時候要重新設置v_widget和controlBar,提示一下如果構造函數中new出來的widget沒有掛靠在其他widget的話記得在析構函數中delete
void DisplayVideo::resizeEvent(QResizeEvent * event)
{
QWidget::resizeEvent(event);
v_widget->resize(event->size());
bar->resize(QSize(event->size().width(), bar->height()));
QPoint point = v_widget->mapToGlobal(QPoint(0, 0));
bar->move(point.x(), point.y() + v_widget->height() - bar->height());
}
void DisplayVideo::moveEvent(QMoveEvent* event)
{
QWidget::moveEvent(event);
//if (bar->isVisible()) {
bar->move(event->pos().x(), event->pos().y() + v_widget->height() - bar->height());
//}
}
- 設置視頻播放速度使用QCombobox,在點擊combobox時出現異常,controlbar會hide所以添加了事件過濾
// controlBar的構造函數添加
ui.comboBox->installEventFilter(this);
bool VideoControlBar::eventFilter(QObject* obj, QEvent* event)
{
if (obj == ui.comboBox && event->type() == QEvent::MouseButtonPress) {
QMouseEvent* mouseEvent = static_cast<QMouseEvent*>(event);
if (mouseEvent->button() == Qt::LeftButton) {
// 阻止事件繼續傳播
event->accept();
ui.comboBox->showPopup();
return true;
}
}
return QWidget::eventFilter(obj, event);
}
- 我現在還沒找到解決方法一個問題就是設置background-color:rgba沒有效果,如果你知道怎么解決,請告訴我


使用QMediaPlayer+QVideoWidget+QAudioOutput實現一個簡單視頻播放器-Qt6.8
浙公網安備 33010602011771號