昨天我看见一个开发者发了一个问题,询问如何播放声音。目前由于一些原因在模拟器中没法测试。其实,播放声音很容易。如果使用qmake的话,可能需要做一些修改才可以正确地在手机上播放。
我们首先使用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: "audio.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(100)
height: units.gu(75)
Page {
title: i18n.tr("Audio")
SoundEffect {
id: bubblepop
source: "bubblepop.wav"
volume: 1.0
}
MediaPlayer {
id: backgroundMusic
source: "background.mp3"
autoPlay: true
loops: MediaPlayer.Infinite
volume: 0.3
}
Row {
anchors.centerIn: parent
Button {
text: "Play bubble"
onClicked: {
bubblepop.play();
}
}
}
}
}
import QtMultimedia 5.0
同时我们使用两种不同的方法来播放声音。这两个声音在播放时可以混在一起。同时,我们要记得做如下的设置:
添加“audio” security policy。由于我们使用qmake,所以在我们的应用中需要修改我们的.pro文件来包含我们的声音文件:
TEMPLATE = aux
TARGET = audio
RESOURCES += audio.qrc
QML_FILES += $$files(*.qml,true) \
$$files(*.js,true) \
$$files(sounds/*.mp3,true) \
$$files(sounds/*.wav,true)
CONF_FILES += audio.apparmor \
audio.desktop \
audio.png
OTHER_FILES += $${CONF_FILES} \
$${QML_FILES}
#specify where the qml/js files are installed to
qml_files.path = /audio
qml_files.files += $${QML_FILES}
#specify where the config files are installed to
config_files.path = /audio
config_files.files += $${CONF_FILES}
INSTALLS+=config_files qml_files
这样在我们的项目中,就会有我们“sounds”目录下的声音文件了。它们可以在我们的QML文件中得到播放。
所有的源码在: https://github.com/liu-xiao-guo/audio
细心的开发者可以发现,虽然Ubuntu手机系统目前是单任务系统,但是当你的应用在播放音乐的时候,随后把它推到后台,一般来说应用会被系统suspend,但是针对音乐的播放,它并没有被停下来.这是一个比较特别的设计.