在这篇文章中,我们将介绍如何在Ubuntu QML应用中播放一个视频。为了实现方便,我们可以事先用手机录下一个视频,并置于我们已经创建好的项目中。
首先,我们利用Ubuntu SDK来创建一个“QML app with Simple UI (qmake)”的项目。我们修改我们的Main.qml文件如下:
import QtQuick 2.0
import Ubuntu.Components 1.1
import QtMultimedia 5.0
/*!
\brief MainView with a Label and Button elements.
*/
MainView {
// objectName for functional testing purposes (autopilot-qt5)
objectName: "mainView"
// Note! applicationName needs to match the "name" field of the click manifest
applicationName: "video.liu-xiao-guo"
/*
This property enables the application to change orientation
when the device is rotated. The default is false.
*/
//automaticOrientation: true
// Removes the old toolbar and enables new features of the new header.
useDeprecatedToolbar: false
width: units.gu(60)
height: units.gu(85)
Page {
title: i18n.tr("Video")
Video {
id: video
anchors.fill: parent
source: "sample.mp4"
focus: true
Keys.onSpacePressed: {
video.playbackState == MediaPlayer.PlayingState ? video.pause() : video.play()
}
Keys.onLeftPressed: video.seek(video.position - 5000)
Keys.onRightPressed: video.seek(video.position + 5000)
}
Button {
anchors.bottom: parent.bottom
anchors.horizontalCenter: parent.horizontalCenter
anchors.bottomMargin: units.gu(1)
text: "Play"
onClicked: {
video.play()
}
}
Image {
id:left
width: units.gu(4)
height: width
anchors.left: parent.left
anchors.bottom: parent.bottom
anchors.leftMargin: units.gu(1)
anchors.bottomMargin: units.gu(1)
source: "icon-left-arrow.png"
MouseArea {
anchors.fill: parent
onClicked: {
video.seek(video.position - 1000);
}
}
}
Image {
id:right
width: units.gu(4)
height: width
mirror: true
anchors.right: parent.right
anchors.bottom: parent.bottom
anchors.rightMargin: units.gu(1)
anchors.bottomMargin: units.gu(1)
source: "icon-left-arrow.png"
MouseArea {
anchors.fill: parent
onClicked: {
video.seek(video.position + 1000);
}
}
}
}
}
这里我们引入了QtMultiMedia库:
import QtMultimedia 5.0
我们需要同时修改我们的.pro文件来安装我们的sample.mp4视频文件到手机中:
TEMPLATE = aux
TARGET = video
RESOURCES += video.qrc
QML_FILES += $$files(*.qml,true) \
$$files(*.js,true) \
$$files(*.mp4,true)
$$files(*,true)
CONF_FILES += video.apparmor \
video.desktop \
video.png
OTHER_FILES += $${CONF_FILES} \
$${QML_FILES}
#specify where the qml/js files are installed to
qml_files.path = /video
qml_files.files += $${QML_FILES}
#specify where the config files are installed to
config_files.path = /video
config_files.files += $${CONF_FILES}
INSTALLS+=config_files qml_files
运行我们的应用,界面显示如下:
我们可以通过左下角和右下角的箭头按钮来快进或后退。按下中间的按钮“Play”可以用来播放视频。
项目的源码在:https://github.com/liu-xiao-guo/video