Silent Metronome in QML
Tonight I could not attend band rehearsal so I used the time to play with the new QML language. There is a nice tutorial online and a good screencast.
QML allows one to write flashy applications with little code. My first QML program is a metronome. The N900 has a metronome program but it is rather boring. It does not look and feel like a real metronome. So I set out to write one in QML and managed to do so in 56 lines of QML. The interaction is simple: tap it to toggle between on and off and slide up and down to move the cross-bar on the metronome which will adjust the tempo in the range 40 to 208 beats per minute.
Without further ado here is the code. You can run it in qmlviewer. Two things are lacking at the moment: a nice SVG image of a metronome and of course the ticking sound. I am keen to find out how to make the metronome produce sound to make it useful.
import Qt 4.6Rectangle {
width: 640
height: 480
Rectangle { // metronome bar
id: bar
x: 320; y: 100; width: 30; height: 300
color: "#aaaaaa"
property double tempo: 120
Rectangle { // weight on metronome bar that determines the tempo
x: -15; y: parent.tempo; width: 60; height: 30
color: "#aaaaaa"
}
transformOrigin: Item.Bottom
rotation: 0
rotation: SequentialAnimation {
id: anim
repeat: true
NumberAnimation { to: 35; easing: "easeInOutQuad"; duration: 60000/bar.tempo }
NumberAnimation { to: -35; easing: "easeInOutQuad"; duration: 60000/bar.tempo }
}
}
Text { // tempo indicator
x: 0; y: 0;
font.pointSize: 24; font.bold: true
text: bar.tempo
}
MouseRegion { // logic for tempo tuning and turning metronome on and off
anchors.fill: parent
property int start: -1
property bool moved: false
property bool wasrunning: true
onReleased: { // start or stop the metronome
anim.running = (moved) ?wasrunning :!wasrunning
bar.rotation = 0
start = -1
}
onPositionChanged: { // adjust the tempo
moved = start != -1
wasrunning = (moved) ?wasrunning :anim.running
bar.tempo += (moved) ?(mouse.y - start) :0
bar.tempo = (bar.tempo > 208) ?208 :bar.tempo
bar.tempo = (bar.tempo < 40) ?40 :bar.tempo
anim.running = false;
bar.rotation = 0
start = mouse.y
}
}
}