Monday, May 13, 2013

A little bit of reusable code Sound Button

Want a button for Ubuntu Components that plays a sound when pressed, and stops when released? Here's SoundButton . Perfect for your typical Sound Board type app.


import QtQuick 2.0
import Ubuntu.Components 0.1
import QtMultimedia 5.0

    Button
    {
        id: soundButton
        property string soundUrl: ""
        onPressedChanged:
        {
            if(pressed)
            {
                audio.play()
            }
            else
            {
                audio.stop()
            }
        }

    Audio
    {
        id: audio
        source:soundButton.soundUrl;
    }
}


6 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. Hey Rick,

    I would do it slightly more QML'ish:

    import QtQuick 2.0
    import Ubuntu.Components 0.1
    import QtMultimedia 5.0

    Button {
    id: soundButton
    property string soundUrl: ""

    Audio {
    id: audio
    source:soundButton.soundUrl;
    playbackState: soundButton.pressed ? Audio.PlayingState : Audio.StoppedState
    }
    }

    try to use as little javascript as possible to speed up your QML application.

    ReplyDelete
    Replies
    1. Thanks Micahel, that is more QMLish. I still have not shaken off my old habits of responding to signals instead of binding to properties. On the other hand, I wonder if my original code might be a bit easier to read?

      Delete
    2. Being the QML newbie that I am, I don't find it hard to read once it's formatted as yours (indent et.al.)

      Delete
  3. Nice code simplification Micahel!
    Although, be careful not to make people think the app will be any faster that way. Reducing the size of the JavaScript will impact performance positively if this code is called very frequently, for example as part of an animation.
    In the case above, it will not make any difference.

    ReplyDelete
  4. Yep, agreed. It doesn't make any real difference here. Its still a good idea to get used to this declarative way of doing things. Its easier to modify the code to add additional states without ending up in endless if/else trees.

    ReplyDelete