Tuesday, July 26, 2016

Learn music for programmers with Sonci Pi - 02 - Random Chinese music generator

If you play just black keys on the piano in randomly you'll generate a Chinese music.

Pentatonic scale


Now this time it makes sense Penta tonic = 5 tones. Which is exactly what it is.
There are several pentatonic scales, but as suggested lets start with black piano keys which are:
C#, D#, F#, G#, A#, c#, d#, f#, g#, a#
However most important is the difference between them if we take the number for those tones from Sonic Pi it's:
62, 64, 67, 69, 71, (74, 76, 79, 81, 83)
Hence differences are:
2, 3, 2, 2, (3, 2, 3, 2, 2)
I guess you can see the pattern there, so if you choose any tone and just do the differences, you got pentatonic scale.

Sonic Pi

OK so musical theory we have, what we will need to create simple generator. Endless loop and randomly choose tone and duration in each go run through in the loop.


Loop

Loop just do commands in endless loop.

loop do
  commands
end

Field

Field is the list of items in square brackets separated by comma(s)
[62, 64, 67, 69, 71]
pentatonic_scale = [62, 64, 67, 69, 71]

Choose

Randomly choose one of the item in the give field
choose(field)
choose([62, 64, 67, 69, 71])

One_in

This returns true with probability of 1/X
one_in(X)
For example gives true with probability of 1/5
one_in(5)

Function/Procedure

Just use define :name do |prametr1, parametr2| to define procedure or function, if you want it to return some value then before the end use name = value

define :gchoose_note do
  note = 67
  note = 64 if one_in(5)
  note = 69 if one_in(5)
  note = 62 if one_in(10)
  note = 71 if one_in(10)
  gchoose_note = note
end

Random Chines music generator v1


loop do
  play choose([62, 64, 67, 69, 71])
  sleep choose([0.125, 0.25, 0.5, 1])
end

The problem with this is that it's too random and it doesn't sound as much as Chines music as if you really play the black keys your self randomly.
The reason is that people often misunderstand the randomness and if you ask group of the people to stay in the room randomly they will distribute them self's more or less evenly.
So they do when the play black keys, they tend to play one tone (in the middle often) and going around back and forth.

Random Chines music generator v2


So let's try a Gaussian distribution of probability with which we choose the tone to play.

# Welcome to Sonic Pi v2.10
use_bpm 60
use_synth :dull_bell

define :gchoose_note do
  note = 67
  note = 64 if one_in(5)
  note = 69 if one_in(5)
  note = 62 if one_in(10)
  note = 71 if one_in(10)
  gchoose_note = note
end

define :gchoose_duration do
  duration = 0.25
  duration = 0.5 if one_in(3)
  duration = 1 if one_in(6)
  duration = 0.125 if one_in(6)
  gchoose_duration = duration
end

loop do
  play gchoose_note
  sleep gchoose_duration
end

No comments: