How to play music in Ubuntu QML, ubuntuqml
Yesterday I saw a developer send a question asking how to play the sound. Currently, it cannot be tested in the simulator for some reasons. In fact, playing sound is very easy. If you use qmake, you may need to make some modifications to play the video correctly on your phone.
First, we use the SDK to create a Simple project (QML app with Simple UI "qmake "). We remember to modify our Main. qml as follows:
import QtQuick 2.0import Ubuntu.Components 1.1import 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(); } } } }}
Here we use the QtMultiMedia library.
import QtMultimedia 5.0
At the same time, we use two different methods to play the sound. These two sounds can be mixed during playback. Make the following settings:
Add "audio" security policy. Because we use qmake, we need to modify our. pro file in our application to include our sound file:
TEMPLATE = auxTARGET = audioRESOURCES += audio.qrcQML_FILES += $$files(*.qml,true) \ $$files(*.js,true) \ $$files(sounds/*.mp3,true) \ $$files(sounds/*.wav,true)CONF_FILES += audio.apparmor \ audio.desktop \ audio.pngOTHER_FILES += $${CONF_FILES} \ $${QML_FILES}#specify where the qml/js files are installed toqml_files.path = /audioqml_files.files += $${QML_FILES}#specify where the config files are installed toconfig_files.path = /audioconfig_files.files += $${CONF_FILES}INSTALLS+=config_files qml_files
In this way, there will be sound files under the "sounds" directory in our project. They can be played in our QML file.
All source code in: git clone https://gitcafe.com/ubuntu/audio.git