summaryrefslogtreecommitdiff
path: root/client/index.js
blob: 3e0e171993cbbf016eb13aa5f0462b2ca14fca39 (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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
import Tone from 'tone'
import WebMidi from 'webmidi'
import Nexus from 'nexusui'
import keys from './lib/keys'
import kalimba from './lib/kalimba'
import scales from './lib/scales'
import { mod, browser, requestAudioContext, ftom, mtof, tap } from './lib/util'

import * as data from './data'

const DEFAULT_BPM = 60

const nx = window.nx = {}

let midi
const note_values = [
  [8, '8 measures'],
  [4, '4 measures'],
  [2, '2 measures'],
  [1, 'whole note'],
  [1/2, 'half note'],
  [1/3, 'third note'],
  [1/4, 'quarter note'],
  [1/5, 'fifth note'],
  [1/6, 'sixth note'],
  [1/8, 'eighth note'],
  [1/10, 'tenth note'],
  [1/12, 'twelfth note'],
  [1/16, 'sixteenth note'],
  [1/32, 'thirtysecond note'],
]


WebMidi.enable(midi_ready)

function midi_ready(err) {
  if (err) {
    console.error('webmidi failed to initialize')
    return
  }
  if (!WebMidi.outputs.length) {
    console.error('no MIDI output found')
    return
  }
  console.log(WebMidi.inputs)
  console.log(WebMidi.outputs)
  if (WebMidi.outputs.length > 1) {
    const filtered = WebMidi.outputs.filter(output => output.name.match(/prodipe/i))
    if (filtered.length) {
      midi = filtered[0]
    }
  }
  midi = midi || WebMidi.outputs[0]
  console.log(midi.name)
}
let i = 0, datasets = {}, dataset = {}, bounds = {}, diff = []
let play_fn = play_sequence
data.load().then(lists => {
  // nx.dataset.choices = Object.keys(lists)
  console.log(lists) 
  datasets = lists
  requestAudioContext(ready)
  pick_dataset('housing costs and income inequality')
})
function pick_dataset(key){
  console.log('pick dataset:', key)
  i = 0
  dataset = datasets[key]
  bounds = get_bounds(dataset)
  diff = get_diff_bounds(bounds.rows)
}
var behaviors = {
  sequence: { name: 'Sequence', fn: play_sequence },
  interval: { name: 'Intervals', fn: play_interval_sequence },
}
function pick_behavior(name){
  behaviors[name].fn()
}
function play_next(){
  let note_time = 120000 / Tone.Transport.bpm.value * note_values[nx.timing.active][0]
  setTimeout(play_next, note_time)
  play_fn(note_time)
}
function play_sequence(){
  play_fn = (note_time) =>  {
    const { rows, min, max } = bounds
    const count = rows.length * rows[0].length
    if (i >= count) i = 0
    const y = Math.floor(i / rows[0].length)
    const x = i % rows[0].length
    if (!x) console.log(y)
    const n = rows[y][x]
    i += 1
    if (i >= count) i = 0;
    play( norm(n, min, max) * nx.multiply.value, note_time * nx.duration.value)
  }
}
function play_interval_sequence(){
  play_fn = (note_time) =>  {
    const { rows, min, max } = bounds
    const count = rows.length
    if (i >= count) i = 0
    const y = i % count
    const row = rows[y]
    if (! row) { i = 0; return }
    const row_min = Math.min.apply(Math, row)
    const row_max = Math.max.apply(Math, row)
    const row_f0 = norm(row_min, min, max)
    const row_root = row_f0 * nx.multiply.value
    row.forEach(n => {
      const note = row_root + norm(n - row_min, diff.min, diff.max) * nx.interval.value
      play(note, note_time * nx.duration.value)
    })
    i += 1
  }
}

function norm(n, min, max){
  return (n - min) / (max - min)
}
function get_diff_bounds(rows){
  const diffs = rows.map(row => {
    const row_min = Math.min.apply(Math, row)
    const row_max = Math.max.apply(Math, row)
    return row_max - row_min
  })
  const min = Math.min.apply(Math, diffs)
  const max = Math.max.apply(Math, diffs)
  return { min, max }
}
function get_bounds(dataset){
  let rows = dataset.lines
  rows.forEach(row => row.shift())
  rows = rows.map(a => a.map(n => parseFloat(n)))
  const max = rows.reduce((a,b) => {
    return b.reduce((z,bb) => {
      return Math.max(z, bb)
    }, a)
  }, -Infinity)
  const min = rows.reduce((a,b) => {
    return b.reduce((z,bb) => {
      return Math.min(z, bb)
    }, a)
  }, Infinity)
  return { rows, max, min }
}
function play(index, duration){
  // console.log(index)
  const scale = scales.current()
  const freq = scale.index(index + Math.round(nx.offset.value), nx.octave.value)
  let midi_note = ftom(freq)
  let cents = midi_note % 1
  if (cents > 0.5) {
    midi_note += 1
    cents -= 1
  }
  cents *= 2
  midi_note = Math.floor(midi_note)
  if (midi) {
    if (midi_note > 127) return
    const note = Tone.Frequency(Math.floor(midi_note), "midi").toNote()
    duration = duration || 60000 / Tone.Transport.bpm.value
    midi.playNote(note, "all", { duration })
    // cents
    // midi.sendPitchBend(cents, "all")
  } else {
    kalimba.play(freq)
  }
}

function update_value_on_change(el, id, is_int, fn) {
  const label = document.querySelector(id + ' + .val')
  const update = v => {
    label.innerHTML = is_int ? parseInt(v) : v.toFixed(2)
    fn && fn(v)
  }
  el.on('change', update)
  update(el.value)
  el.update = update
}
function update_radio_value_on_change(el, id, values, fn) {
  let old_v = el.active
  const label = document.querySelector(id + ' + .val')
  const update = v => {
    if (v === -1) {
      v = el.active = old_v
    } else {
      old_v = v
    }
    label.innerHTML = values[v][1]
    fn && fn(v)
  }
  el.on('change', update)
  update(el.active)
  el.update = update
}
function build_options(el, lists, fn) {
  Object.keys(lists).forEach( (key, i) => {
    const list = lists[key]
    const option = document.createElement('option')
    option.innerHTML = list.name
    option.value = key
    el.appendChild(option)
  })
  el.addEventListener('input', function(e){
    fn(e.target.value)
  })
}
function ready () {
  scales.build_options(document.querySelector('#scale'))
  build_options(document.querySelector('#dataset'), datasets, pick_dataset)
  build_options(document.querySelector('#behavior'), behaviors, pick_behavior)
  // nx.colorize('#f4d142')

	Tone.Transport.bpm.value = DEFAULT_BPM
  nx.tempo = new Nexus.Dial('#tempo', {
    min: 10,
    max: 300,
    step: 1,
    value: DEFAULT_BPM,
  })
  update_value_on_change(nx.tempo, '#tempo', true, v => Tone.Transport.bpm.value = v)

  nx.timing = new Nexus.RadioButton('#timing', {
    size: [400,25],
    numberOfButtons: note_values.length,
    active: 6,
  })
  update_radio_value_on_change(nx.timing, '#timing', note_values)

  nx.duration = new Nexus.Dial('#duration', {
    min: 0,
    max: 2,
    step: 0.01,
    value: 0.8,
  })
  update_value_on_change(nx.duration, '#duration', false)

  nx.offset = new Nexus.Dial('#offset', {
    min: -24,
    max: 24,
    step: 1,
    value: 0,
  })
  update_value_on_change(nx.offset, '#offset', true)

  nx.octave = new Nexus.Dial('#octave', {
    min: -4,
    max: 4,
    step: 1,
    value: 0,
  })
  update_value_on_change(nx.octave, '#octave', true)

  nx.multiply = new Nexus.Dial('#multiply', {
    min: -64,
    max: 64,
    step: 1,
    value: 7,
  })
  update_value_on_change(nx.multiply, '#multiply', true)

  nx.interval = new Nexus.Dial('#interval', {
    min: -64,
    max: 64,
    step: 1,
    value: 10,
  })
  update_value_on_change(nx.interval, '#interval', true)

  document.querySelector('.loading').classList.remove('loading')
  play_next()
}

keys.listen(index => {
  nx.offset.value = index
  nx.offset.update(index)
})