aboutsummaryrefslogtreecommitdiff
path: root/examples/2-sqlite-krate.csd
blob: d6a370fd742d019ddf6680efcfeac1182b6a8328 (plain)
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
<CsoundSynthesizer>
<CsOptions>
-odac
</CsOptions>
<CsInstruments>
/*
    EXAMPLE 2

    Use a metro to trigger the insertion of points from a line into a sqlite database,
    then read back the points in reverse order and play back with enveloping
    

*/

sr = 44100
kr = 4410
nchnls = 2
0dbfs = 1
seed 0


; sqlite3 takes a file path, or :memory: for a temporary in-memory database
;gidb dbconnect "sqlite", ":memory:"
gidb dbconnect "sqlite", "/tmp/example.db"


instr start_example

    ; create the table with just one float column
    kdone1 dbexec_k gidb, "CREATE TABLE IF NOT EXISTS frequencies (freq float)", -1

    ; execute when create table statement has completed - clear out if the table does exist 
    kdone2 dbexec_k gidb, "DELETE FROM frequencies", kdone1
    
    ; execute when delete has completed
    schedkwhen kdone2, 0, 0, "db_insert", 0, 5
    schedkwhen kdone2, 0, 0, "db_select", 5, 10


endin


; insert frequency values from line into database at k rate
instr db_insert

    ; generate some data and print
    kfreq line 440, p3, 1000
    ktrigger metro 5
    printk 0.2, kfreq

    ; insert snapshot with each metro (as long as the last query is still not pending)
    Squery sprintfk "INSERT INTO frequencies (freq) VALUES (%f)", kfreq
    kdone dbexec_k gidb, Squery, ktrigger
    
endin


; read frequency values from database at i rate: obtain the values in reverse order 
instr db_select

    ; get all values in descending order into an array
    ires[][] dbarray gidb, "SELECT freq FROM frequencies ORDER BY freq desc"
    itimestep = 0.3
    index = 0
    itime = 0
    ilast = 0

    ; loop through the values and play the frequency with some basic interpolation between last current values
    while (index < lenarray(ires)) do
        if (ilast != 0) then
            event_i "i", "playpitch", itime, itimestep, ilast, ires[index][0]
        endif
        ilast = ires[index][0]
        index += 1
        itime += itimestep * 0.8
    od
endin


; basic oscillator instrument with envelope
instr playpitch
    ipitch1 = p4
    ipitch2 = p5
    kamp linseg 0, p3*0.2, 1, p3*0.6, 1, p3*0.2, 0
    kpitch line ipitch1, p3, ipitch2
    aout oscil 0.8, kpitch
    outs aout*kamp, aout*kamp
endin

</CsInstruments>
<CsScore>
i "start_example" 0 15

</CsScore>
</CsoundSynthesizer>