如何在Ubuntu QML应用中播放音乐

185 篇文章 6 订阅
159 篇文章 2 订阅

昨天我看见一个开发者发了一个问题,询问如何播放声音。目前由于一些原因在模拟器中没法测试。其实,播放声音很容易。如果使用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();
                }
            }
        }

    }
}


这里我们使用了QtMultiMedia库。


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,但是针对音乐的播放,它并没有被停下来.这是一个比较特别的设计.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值