I would like to write a Mathematica routine for generating random musical melodies that obey (some of) the constraints of traditional tonal harmony. For simplicity’s sake, I’m interested only in strictly diatonic melodies in a major key.

Assuming that all the note values in the melody are equal (whole notes, say), I simply represent the diatonic scale degrees of the major key by the integers 1 to 7. The harmonic constraints that I wish to implement are then as follows:

- The degrees 1, 3, 5 can move, by step or by leap, to any other scale degree.
- Degree 2 can move to either 1 or 3, with a slight stochastic bias towards 1.
- Degree 4 moves to 3.
- Degree 6 moves to 5.
- Degree 7 moves to 1.
- The "natural" tendencies of scale degrees 2, 4, 6, 7, as outlined above, can be negated by stepwise movement, up or down, along the major scale. For example: 7 – 6 in isolation is not allowed, but 1 – 7 – 6 or 7 – 6 – 5 is. The relative frequency of such scalar movements should preferably be (very roughly) proportional to the length of the scale fragment. For example, 1 – 7 – 6 – 5 – 4 should occur "more often" than just 1 – 7 – 6.
- Melodies should begin with one of the scale degrees 1, 3, 5, and end with one of the formulas 7 – 1, 2 – 1, 4 – 3, or 2 – 3.
- For bass melodies, I would instead of (7) like to have the optional constraint that all melodies end with the cadential formula 5 – 1.
- Melodies may be any length between 5 and 16 notes.
- Stepwise motion should predominate over leaps, in roughly the ratio 4 to 1.

Finally, if it’s possible, I’d like to have a function to put the generated melody into an audible form.

A tall order perhaps, but any suggestions would be appreciated, even if they solve my problem only partially.