New PlayTone() function

AppStudio has had a PlaySound() function for some time which lets you play mp3 and other sound files. In AppStudio 5.2, we added a PlayTone() function, which lets you play sounds with a specific frequency, duration and optional volume.

Tones can provide useful feedback to users. They can also be used to for games, melodies and even to create musical instruments.

Here is how it looks:

PlayTone(440, 1000)

This plays a middle A for 1 second.

PlayTone() is asynchronous: execution continues on the next statement, whether the note is complete or not. This lets us play chords:

Dim C = 261.63
Dim E = 329.63
Dim G = 392.00
PlayTone(C, 1000)
PlayTone(E, 1000)
PlayTone(G, 1000)

This plays the common C-E-G chord for one second.

There is much more that can be done with this function. It has a return value, which is the tone object. That tone object can be manipulated. For example,

'Play a tone for 10 seconds
tone = PlayTone(440, 10000)

Function Button1_click()
  tone.oscillator.stop()
End Function

This plays a tone for 10 seconds, or less if Button1 is clicked.

You can also call a function when the tone completes. Using this, you could write a sequence of notes:

tone = PlayTone(440, 1000)
tone.oscillator.onended = NextTone

Function NextTone()
  'This function is called after 1 second
End Function

There are many more things which can be done. Mozilla has documentation here.