Play random sound within range.

Hello all,

Trying to make a solfege program here.
With GUI-buttons I have laid out a piano keyboard, each button triggers a pianosound to be played at a certain pitch.
The button also triggers a function PlayInterval which after waiting with a ‘yiels’ is supposed to play another (random) pianosound within a certain range from the first.

I have a var ‘FirstNote’ (integer ranging from ‘1-88’)
I have an ‘Interval’ (random integer within a range starting from ‘FirstNote’)
I have 21 audio-clips, each one to be played at 4 different pitches.

What would be the neatest way of doing this, do I use an array or something similar?

Thanks, Robert

The initial random number can be chosen with Random.Range. With this and most other integer ranges, you can often save yourself work by starting at zero (so here you would number the keys from 0 to 87 rather than 1 to 88 ). You can choose a random offset from a key number, again by using Random.Range. However, as you get to the high numbered keys, you will need to make sure that the offset can’t generate a key number greater than 87. You can use Mathf.Clamp to limit the range:-

var intervalKey = Mathf.Clamp(keyNumber + Random.Range(0, 12), 0, 87);

I’m guessing that the reason for the 21 audio clips is so that each one doesn’t need to have its pitch altered too much (although don’t you need 22 clips for 88 keys? :wink: ) If this is what you are doing, you could handle it by keeping the clips in an array. You can then map a key number to a clip index by dividing by four and then using Mathf.FloorToInt to make sure the value doesn’t get rounded up:-

var clipNum = Mathf.FloorToInt(keyNumber / 4);

To identify which of the four keys mapped to the sample was pressed, use the modulo operator:-

var keyInRange = keyNumber % 4;  // Gives a number from 0 to 3