# Happy New Year!

Join the DZone community and get the full member experience.

Join For Freemy previous new year posts were about drawing pictures in sql: snowflakes , clocks , fractals and even our planet earth as seen from above.

but contrary to the popular belief, sql is not just about graphics processing. you can use it for all kinds of things.

today we'll use sql to create music.

remember those polyphonic ringtones in early 2000's cell phones? instead of downloading mp3's (which were a pain to download and even more pain to upload them to the phone), you could type in the notes and their values, and the phone would play them for you.

most phones played tunes in a very straightforward way: for each note, they calculated its frequency and generated a pure sine waveform of this frequency. polyphonic phones could play several notes at once: this would require two or more superimposed waveforms. math behind that are very simple: channel amplitude is a sine function of time and frequency, and all the channel amplitudes are added together.

let's do this too and play some new year music with postgresql.

### notation

to define a note, we need to tell the system its pitch (how high or low it is) and value (how long to keep it playing). for simplicity, we assume all our notes have the same volume. we would also need a way to mark rests (pauses).

letters
```
a
```

to
```
g
```

will define pitch (the way they normally do). the uppercase letters will define pitches c
_{
4
}
to b
_{
4
}
(in scientific notation), the lowercase would define pitches c
_{
3
}
to b
_{
3
}
. a sharp sign (
```
#
```

) may follow a letter, meaning what the sharp sign normally does (increases pitch by half-tone). if we want to go beyond the two basic octaves, we would append one or more the plus signs
```
+
```

to the note, so
```
d++
```

would mean d
_{
6
}
, and
```
d++
```

would mean d
_{
1
}
. the letter
```
p
```

(in either case) would define a rest.

the pitch (or rest) may be followed by a number, which would define the note value (relative duration). 1 would stand for an eighth, 2 for a quarter etc. for simplicity, we won't use shorter values. if the number is omitted, the note would be considered an eighth.

finally, all notes might be separated with spaces which mean nothing and are only used to improve legibility.

here's a sample of what the score could look like:

with tracks (track, data) as ( values (1, 'cdefgabc2'), (2, 'cdefgabc+2') ) select * from tracks

that's just two c scales one octave apart from each other, with the final notes being quarters (twice as long as the others).

### parameters

we need to define some basic parameters of our music, namely: sample rate (for digitizing), tempo (how long does an eighth note last) and fade length. fading in and out will make the music sound more natural.

to do this, we'll throw in another cte:

with tracks (track, data) as ( values (1, 'cdefgabc2'), (2, 'cdefgabc+2') ), options as ( select 44100 as rate, ( select count(*) from tracks ) tcnt, 0.15 as eighth, 0.0625 as fade ) select * from options

here we define the basic parameters and also calculate the number of tracks (it will come in handy on later steps).

### parsing

to parse our notation, we'll use three steps.

first, we get rid of the spaces and split the string into a table of notes (a letter with a possible sharp symbol and value). to do this, we use postgresql's
```
regexp_split_to_table
```

and split by empty strings or space sequences followed by a letter:

with tracks (track, data) as ( values (1, 'cdefgabc2'), (2, 'cdefgabc+2') ), options as ( select 44100 as rate, ( select count(*) from tracks ) tcnt, 0.15 as eighth, 0.0625 as fade ), notes (track, note) as ( select track, regexp_split_to_table(data, '\s*(?=[a-ga-gp])') from tracks ) select * from notes

this gives us each note on its row, along with the track number.

second, given a pitch, we need to define frequency.

we will use equal temperament with a440 pitch standard. this means that frequency ratio of all adjacent half-tones is 2
^{
1/12
}
, and the frequency of a
_{
4
}
is exactly 440 hz. to know frequency of any given pitch, we would need to count how many half-tones apart from a
_{
4
}
it is, raise 2
^{
1/12
}
to this power and multiply or divide 440 by the result.

since our notes are defined by letters and sharp signs, it would be easiest to build a lookup table with half-tone distances:

with tracks (track, data) as ( values (1, 'cdefgabc'), (2, 'cdefgabc+') ), options as ( select 44100 as rate, ( select count(*) from tracks ) tcnt, 0.15 as eighth, 0.0625 as fade ), notes (track, note) as ( select track, regexp_split_to_table(data, '\s*(?=[a-ga-gp])') from tracks ), scale (shift, note) as ( values (-9, 'c'), (-8, 'c#'), (-7, 'd'), (-6, 'd#'), (-5, 'e'), (-4, 'f'), (-3, 'f#'), (-2, 'g'), (-1, 'g#'), (0, 'a'), (1, 'a#'), (2, 'b') ) select * from scale

finally, we calculate physical parameters (duration and frequency) for each note. we apply a regular expression to isolate pitch, octave, sharp and value. once we know them, we can substitute them into a formula and get the parameters:

with tracks (track, data) as ( values (1, 'cdefgabc2'), (2, 'cdefgabc+2') ), options as ( select 44100 as rate, ( select count(*) from tracks ) tcnt, 0.15 as eighth, 0.0625 as fade ), notes (track, note) as ( select track, regexp_split_to_table(data, '\s*(?=[a-ga-gp])') from tracks ), scale (shift, note) as ( values (-9, 'c'), (-8, 'c#'), (-7, 'd'), (-6, 'd#'), (-5, 'e'), (-4, 'f'), (-3, 'f#'), (-2, 'g'), (-1, 'g#'), (0, 'a'), (1, 'a#'), (2, 'b') ), params as ( select *, 440 * power(2, octave + shift / 12.0) as frequency from ( select track, number, upper(substr(digits[1], 1, 1)) || digits[2] as note, case when digits[1] ~ e'[a-g]' then length(digits[1]) else 1 - length(digits[1]) end as octave, coalesce(nullif(digits[3], '')::integer, 1) as value from ( select track, row_number() over (partition by track) number, regexp_matches(note, '([a-ga-gp]\+*)(#?)(\d*)') digits from notes ) q cross join options ) q left join scale using (note) ) select * from params

this way, we have all note parameters nicely presented in a table: track, ordinal number in the track, octave; and, most important, value and frequency.

### digitizing

now that we have all parameters, we need to build waveforms out of them.

to do this, we would need to generate a large resultset which would contain as many records as there are samples. the number of samples would be equal to the sample rate times the length of an eighth note times the total number of the notes.

once we have the sample resultset, we need to find the value of each sample. to do this, we join the resultset with the notes cte we generated earlier. the join condition should be so that each note is played on its time.

however, on this stage we don't the the absolute start and end times of the notes yet, just their order and values. we would need to expand the previous cte a little: calculate the absolute start and end times (in eighths), using a window function; and duplicate each note record so that it's repeated as many times as the note longs (again, in eighths). the latter step might seem redundant, but it improves the overall query performance.

with tracks (track, data) as ( values (1, 'cdefgabc2'), (2, 'cdefgabc+2') ), options as ( select 44100 as rate, ( select count(*) from tracks ) tcnt, 0.15 as eighth, 0.0625 as fade ), notes (track, note) as ( select track, regexp_split_to_table(data, '\s*(?=[a-ga-gp])') from tracks ), scale (shift, note) as ( values (-9, 'c'), (-8, 'c#'), (-7, 'd'), (-6, 'd#'), (-5, 'e'), (-4, 'f'), (-3, 'f#'), (-2, 'g'), (-1, 'g#'), (0, 'a'), (1, 'a#'), (2, 'b') ), params as ( select *, 440 * power(2, octave + shift / 12.0) as frequency from ( select track, number, upper(substr(digits[1], 1, 1)) || digits[2] as note, case when digits[1] ~ e'[a-g]' then length(digits[1]) else 1 - length(digits[1]) end as octave, coalesce(nullif(digits[3], '')::integer, 1) as value from ( select track, row_number() over (partition by track) number, regexp_matches(note, '([a-ga-gp]\+*)(#?)(\d*)') digits from notes ) q cross join options ) q left join scale using (note) ), times as ( select *, generate_series(start, start + value - 1) ts from ( select *, sum(value) over (partition by track order by number) - value as start from params ) q ) select * from times

the last note in each track is a quarter, so in our new resultset it's returned twice. we also have an additional field,
```
ts
```

, which means "this note sounds at this beat", beats being counted from the beginning of the piece.

now we can generate the sample recordset, calculate each sample value and return it along with each sample number. the sample value is a sum of sine functions for each note which sounds during this sample.

sine takes values from -1 to 1, and the samples can take values from -32768 to 32767 (we use 16-bit samples). so we need to normalize the value: multiply the sum of sines, by, say, 30000 and divide by the number of tracks, so that no clipping would occur.

we also need to enable fading in and out. to do this we would make the wave amplitude gradually increase and decrease as the samples are taken close to beginning and end of the notes. we would multiply the sine by increasing or decreasing linear function of time, making sure its value does not go beyond 1.

with tracks (track, data) as ( values (1, 'cdefgabc2'), (2, 'cdefgabc+2') ), options as ( select 44100 as rate, ( select count(*) from tracks ) tcnt, 0.15 as eighth, 0.0625 as fade ), notes (track, note) as ( select track, regexp_split_to_table(data, '\s*(?=[a-ga-gp])') from tracks ), scale (shift, note) as ( values (-9, 'c'), (-8, 'c#'), (-7, 'd'), (-6, 'd#'), (-5, 'e'), (-4, 'f'), (-3, 'f#'), (-2, 'g'), (-1, 'g#'), (0, 'a'), (1, 'a#'), (2, 'b') ), params as ( select *, 440 * power(2, octave + shift / 12.0) as frequency from ( select track, number, upper(substr(digits[1], 1, 1)) || digits[2] as note, case when digits[1] ~ e'[a-g]' then length(digits[1]) else 1 - length(digits[1]) end as octave, coalesce(nullif(digits[3], '')::integer, 1) as value from ( select track, row_number() over (partition by track) number, regexp_matches(note, '([a-ga-gp]\+*)(#?)(\d*)') digits from notes ) q cross join options ) q left join scale using (note) ), times as ( select *, generate_series(start, start + value - 1) ts from ( select *, sum(value) over (partition by track order by number) - value as start from params ) q ) select tick, coalesce((amp * 30000 / tcnt)::integer, 0) sample from ( select tick, sum(sin(frequency * 2 * pi() * tick / rate) * least((start + value - cts) / fade, (cts - start) / fade, 1)) as amp from ( select *, tick / eighth / rate as cts from ( select *, generate_series(0, (maxts * rate * eighth)::bigint - 1) tick from ( select max(ts) as maxts from times ) q cross join options ) q ) beat left join times on ts = floor(cts) and cts >= start and cts < start + value group by tick ) q cross join options order by tick limit 50

those are first 50 samples of our digitized music.

let's see how they look on a graph:

with tracks (track, data) as ( values (1, 'cdefgabc2'), (2, 'cdefgabc+2') ), options as ( select 44100 as rate, ( select count(*) from tracks ) tcnt, 0.15 as eighth, 0.0625 as fade ), notes (track, note) as ( select track, regexp_split_to_table(data, '\s*(?=[a-ga-gp])') from tracks ), scale (shift, note) as ( values (-9, 'c'), (-8, 'c#'), (-7, 'd'), (-6, 'd#'), (-5, 'e'), (-4, 'f'), (-3, 'f#'), (-2, 'g'), (-1, 'g#'), (0, 'a'), (1, 'a#'), (2, 'b') ), params as ( select *, 440 * power(2, octave + shift / 12.0) as frequency from ( select track, number, upper(substr(digits[1], 1, 1)) || digits[2] as note, case when digits[1] ~ e'[a-g]' then length(digits[1]) else 1 - length(digits[1]) end as octave, coalesce(nullif(digits[3], '')::integer, 1) as value from ( select track, row_number() over (partition by track) number, regexp_matches(note, '([a-ga-gp]\+*)(#?)(\d*)') digits from notes ) q cross join options ) q left join scale using (note) ), times as ( select *, generate_series(start, start + value - 1) ts from ( select *, sum(value) over (partition by track order by number) - value as start from params ) q ) select string_agg(case when floor(sample / 30000.00 * 20) = y then 'x' else ' ' end, '' order by tick) r from ( select tick, coalesce((amp * 30000 / tcnt)::integer, 0) sample from ( select tick, sum(sin(frequency * 2 * pi() * tick / rate) * least((start + value - cts) / fade, (cts - start) / fade, 1)) as amp from ( select *, tick / eighth / rate as cts from ( select *, generate_series(0, (maxts * rate * eighth)::bigint - 1) tick from ( select max(ts) as maxts from times ) q cross join options ) q ) beat left join times on ts = floor(cts) and cts >= start and cts < start + value group by tick ) q cross join options where tick % 5 = 0 order by tick limit 100 ) x cross join ( select y from generate_series(-20, 20) y ) y group by y order by y

[

*note*]

**:**see original blog post for full output
those are two superimposed sine waveforms (for с
_{
3
}
and c
_{
4
}
) which are gradually fading in as the notes start playing.

for the graph, i took 100 samples and used subsampling (only each 5th sample is shown), as the notes' frequencies are relatively low and the waves are too wide to fit on the screen.

### playing

to play the notes, we need to save our waveforms into a file. unfortunately, native postgresql query tool, psql, is not binary friendly. to save music into a file, we'll have to employ some unix shell magic.

we would need to join our samples into a large hex-escaped string, append the riff headers and use bash's
```
echo
```

to convert from escaped string to binary.

let's create a more complex music piece and dump it into a file.

first, let's create a file called
```
bells.sql
```

and paste this query there:

with tracks (track, data) as ( -- 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 values (1, 'd2 b2 a2 g2 d4 p2 d1d1 d2 b2 a2 g2 e4 p2 e2 e2 c+2 b2 a2 f#4 p2 f#2 d+2 d+2 c+2 a2 g4 p2 d2 d2 b2 a2 g2 d4 p3 d1 d2 b2 a2 g2 e4 p2 e2 e2 c+2 b2 a2 d+2 d+2 d+2 d+2 e+2 d+2 c+2 a2 g4 d+4 b2 b2 b4 b2 b2 b4 b2 d+2 g3 a1 b8 c+2 c+2 c+3 c+1 c+2 b2 b2 b1 b1 b2 a2 a2 b2 a4 d+4 b2 b2 b4 b2 b2 b4 b2 d+2 g3 a1 b8 c+2 c+2 c+3 c+1 c+2 b2 b2 b1 b1 d+2 d+2 c+2 a2 g6 p2'), (2, 'd2 d2 d2 g2 d6 d1d1 d2 d2 d2 b2 e6 p2 e2 e2 b2 c2 f#6 p2 d+2 d+2 c+2 a2 b8 d2 b2 a2 g2 d6 p2 d2 d2 a2 g2 e6 e2 e2 e2 b2 a2 d+2 d+2 d+2 d+2 e+2 d+2 c+2 a2 g4 d+4 b2 b2 b4 b2 b2 b4 b2 d+2 g3 a1 b8 c+2 c+2 c+3 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2 b2 c4 a2 g2 c4 a4 d4 b2 a2 d4 a4 g2 f#2 e2 d2 g4 d4 g4 e2 d2 g4 a2 b2 c4 a2 g2 c4 a4 d4 d4 d4 d2 f#2 g2 e2 d4 g2 f#2 e2 d2 g2 f#2 e2 d2 g2 f#2 e2 d2 g2 g2 a2 b2 c4 b2 a2 g4 e2 d2 a4 b2 c#2 d2 d2 e2 f#2 g2 f#2 e2 d2 g2 f#2 e2 d2 g2 f#2 e2 d2 g2 g2 a2 b2 c4 b2 a2 g4 d4 d4 d4 g2 d2 g2 p2') ), options as ( select 44100 as rate, ( select count(*) from tracks ) tcnt, 0.15 as eighth, 0.0625 as fade ), notes (track, note) as ( select track, regexp_split_to_table(data, '\s*(?=[a-ga-gp])') from tracks ), scale (shift, note) as ( values (-9, 'c'), (-8, 'c#'), (-7, 'd'), (-6, 'd#'), (-5, 'e'), (-4, 'f'), (-3, 'f#'), (-2, 'g'), (-1, 'g#'), (0, 'a'), (1, 'a#'), (2, 'b') ), params as ( select *, 440 * power(2, octave + shift / 12.0) as frequency from ( select track, number, upper(substr(digits[1], 1, 1)) || digits[2] as note, case when digits[1] ~ e'[a-g]' then length(digits[1]) else 1 - length(digits[1]) end as octave, coalesce(nullif(digits[3], '')::integer, 1) as value from ( select track, row_number() over (partition by track) number, regexp_matches(note, '([a-ga-gp]\+*)(#?)(\d*)') digits from notes ) q cross join options ) q left join scale using (note) ), times as ( select *, generate_series(start, start + value - 1) ts from ( select *, sum(value) over (partition by track order by number) - value as start from params ) q ) select 'riff' || ( select string_agg('\x' || to_hex((v >> o) & 255), '' order by o) from ( select len * 2 + 36 v, o from generate_series(0, 24, 8) o ) q ) || 'wavefmt ' || '\x10\x00\x00\x00' || -- subchunk1size '\x01\x00' || -- audioformat '\x01\x00' || -- numchannels ( select string_agg('\x' || to_hex((v >> o) & 255), '' order by o) from ( select rate v, o from generate_series(0, 24, 8) o ) q ) || -- samplerate ( select string_agg('\x' || to_hex((v >> o) & 255), '' order by o) from ( select rate * 2 v, o from generate_series(0, 24, 8) o ) q ) || -- byterate '\x02\x00' || -- blockalign '\x10\x00' || -- bitspersample 'data' || ( select string_agg('\x' || to_hex((v >> o) & 255), '' order by o) from ( select len * 2 v, o from generate_series(0, 24, 8) o ) q ) || d from ( select count(*) as len, string_agg('\x' || to_hex(sample & 255) || '\x' || to_hex((sample >> 8) & 255), '' order by tick) d from ( select tick, coalesce((amp * 30000 / tcnt)::integer, 0) sample from ( select tick, sum(sin(frequency * 2 * pi() * tick / rate) * least((start + value - cts) / fade, (cts - start) / fade, 1)) as amp from ( select *, tick / eighth / rate as cts from ( select *, generate_series(0, (maxts * rate * eighth)::bigint - 1) tick from ( select max(ts) as maxts from times ) q cross join options ) q ) beat left join times on ts = floor(cts) and cts >= start and cts < start + value group by tick ) q cross join options ) q ) q cross join options;

then, let's run this:

echo -ne $(psql postgres -axtf bells.sql) > bells.wav

```
```

on output, we receive a .wav file which we can play with any multimedia player:

download bells.wav (if your browser does not play it).

**happy new year!**

Published at DZone with permission of Alex Bolenok, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Comments