C++中QMediaPlayer在QML中播放實現
阿新 • • 發佈:2019-02-13
1、mediaplayer.h
#ifndef MYMEDIAPLAYER_H #define MYMEDIAPLAYER_H #include <QMediaPlayer> #include <QAbstractVideoSurface> class MyMediaPlayer: public QMediaPlayer { Q_OBJECT public: Q_PROPERTY(QAbstractVideoSurface* videoSurface READ getVideoSurface WRITE setVideoSurface ) Q_INVOKABLE void play(); public: MyMediaPlayer(QObject * parent = 0, Flags flags = 0); public slots: void setVideoSurface(QAbstractVideoSurface* surface); QAbstractVideoSurface* getVideoSurface(); void OnMetaDataAvailableChanged(bool available); private: QAbstractVideoSurface* m_surface; }; #endif // MYMEDIAPLAYER_H
2、mediaplayer.cpp
#include "mymediaplayer.h" void MyMediaPlayer::play() { qDebug()<<"play..."; QMediaPlayer::setMedia(QUrl::fromLocalFile("D:/KuGou/MV/mv.mp4")); QMediaPlayer::play(); QString strTitle = QMediaPlayer::metaData("Title").toString(); QString strSize= QMediaPlayer::metaData("Size").toString(); qDebug()<<"title: " + strTitle + "size: "+ strSize; } MyMediaPlayer::MyMediaPlayer(QObject* parent, Flags flags): QMediaPlayer(parent, flags) { connect(this, SIGNAL(metaDataAvailableChanged(bool)), this, SLOT(OnMetaDataAvailableChanged(bool))); } void MyMediaPlayer::setVideoSurface(QAbstractVideoSurface* surface) { qDebug() << "Changing surface"; m_surface = surface; setVideoOutput(m_surface); } QAbstractVideoSurface* MyMediaPlayer::getVideoSurface() { return m_surface; } void MyMediaPlayer::OnMetaDataAvailableChanged(bool available) { // 資料顯示 qDebug() << "OnMetaDataAvailableChanged"; if(available){ foreach(QString str,availableMetaData()){ qDebug()<<str<<" :"<<metaData(str).toString().toUtf8().data(); } //playlist->setCurrentIndex(++count); } }
3、qml 檔案
import QtQuick 2.6 import QtQuick.Window 2.2 import QtMultimedia 5.6 import QtQuick.Controls 1.4 Window { visible: true width: 640 height: 480 title: qsTr("Hello World") Button { id: play; width: 120; height: 60; text: qsTr("播放") onClicked: { console.log("clicked button"); mymediaplayer.play(); } } VideoOutput { id: videooutput anchors.top: play.bottom; width: 320 height: 240 source: mymediaplayer } }
4、main.cpp
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include "mymediaplayer.h"
#include <QQmlContext>
using namespace std;
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
MyMediaPlayer* player = new MyMediaPlayer();
QQmlApplicationEngine engine;
engine.rootContext()->setContextProperty("mymediaplayer", player);
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
return app.exec();
}
參考:點選開啟連結