-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjCutSamps.py
More file actions
653 lines (506 loc) · 16.5 KB
/
Copy pathjCutSamps.py
File metadata and controls
653 lines (506 loc) · 16.5 KB
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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
# Chop a wave file into separate sample files.
# For use in building soundfonts.
#
# If we add an option to omit detecting the pitch, it could
# be used for chopping a set into individual songs. We'd
# also want to adjust the lead time to a second or two.
import sys
import math
import time
import profile
import warnings
import glob
import jwave
import jtime
import jmidi
import jtrans
# user configurable parameters
_trig_db = -36.0 # dB, trigger level
_default_noise = -50.0 # dB, default noise level when can't measure it.
_noise_delta = 1.0 # dB, level above initial noise level to find sample end
_dwell_time = 0.25 # seconds of sample to keep after level reaches noise level
_lead_time = 0.0 # seconds to keep before start of note
_min_duration = 1.00 # seconds, minimum note duration.
_max_duration = 60.0 # seconds, maximum note duration.
_folder = ""
_fn_prefix = ""
_fn_suffix = ""
# constants
_min_freq = 27 # Hz, lowest note frequency
_max_freq = 4410 # Hz, highest note frequency (4186.0 = C8)
# tweak parameters
_calcs_per_sec = 5 # Number of RMS calcs per second, to detect note end
_lead_crossings = 2 # Number of zero crossings to find start of note
# Operating controls
_log_pitch = False
_dry_run = False # if True, don't actually create any files.
_find_note = True # whether to add note number to file names
_debug = False
_verbose = True
# Find the next sample
def find_trigger(wave, start_sn, trig_dB):
trigger = wave.dB2v(trig_dB)
samp_num = start_sn
wave.seekSample(samp_num)
while True:
try:
samp = wave.readSample()
except IndexError:
return 0
if abs(samp[0]) > trigger:
break;
samp_num += 1
# we've found a trigger.
return samp_num
#
# Measure the RMS level starting at the given sample, for the given duration.
#
def measure_rms(wave, start_sn, duration):
if duration < wave.fmt.sampleRate / 200:
return 0.0
wave.seekSample(start_sn)
buf = jwave.Rmsbuf(wave)
for samp_num in range(start_sn, start_sn + duration):
samp = wave.readSample()
buf.add(buf, samp[0])
return buf.getRms()
def r(samps, delta, length):
sum = 0L
for sn in range(1, length):
sum += abs(samps[sn] - samps[sn + delta])
return sum
def find_pitch(wave, start):
global _pitchlog
start += wave.fmt.sampleRate / 4
# Get a buffer of samples for finding the pitch
end = min(wave.numSamples-1, start + 4 * wave.fmt.sampleRate)
samps = wave.readChan(0, start, end)
buflen = len(samps)
# autocorrelation method for finding pitch
# Define the autocorrelation function r(delta) defined as the sum of the
# pointwise absolute difference between the val(t) and val(t + delta).
# Find the lowest local minimum in r(delta).
# Ignore noise in r(delta) using a latch filter with a miniumum deadband
# (# samples elapsed since the minimum changed)
# find the first sustained maximum.
latch = 3
maxr = 0L
maxt = 0
step = 12.0
rate = 1.0 * wave.fmt.sampleRate
note = 100.0
delta = 4
# for delta in range(wave.fmt.sampleRate / _max_freq, wave.fmt.sampleRate / _min_freq):
while delta < wave.fmt.sampleRate / _min_freq:
cur = r(samps, delta, buflen / 2)
if _log_pitch:
print >>_pitchlog, wave.fmt.sampleRate / delta, ",", cur
if cur > maxr:
maxr = cur
maxt = delta
if maxt != 0 and delta - maxt >= latch:
break
d2 = int(rate / pow(2, (step * math.log(rate / delta, 2) - 1) / step))
delta = max(d2, delta + 1)
last_note = note
note = 12 * math.log(rate/delta)
# print "delta = %d, f = %d, note = %5.1f, diff = %5.1f" % (
# delta, rate/delta, note, last_note - note)
else:
print " Can't find pitch (1)."
print " maxt", maxt
print " delta", delta
print " latch", latch
return 0
# raise Exception("Sample too short (1)")
# find the next local minumum.
minr = 0x7fffffffffffffffL
mint = 0
limit = maxr / 3
# for delta in range(delta + 1, wave.fmt.sampleRate / _min_freq):
while delta < wave.fmt.sampleRate / _min_freq:
cur = r(samps, delta, buflen / 2)
if _log_pitch:
print >>_pitchlog, wave.fmt.sampleRate / delta, ",", cur
if cur < minr:
minr = cur
mint = delta
if mint != 0 and delta - mint >= latch:
if minr < limit:
if not _log_pitch:
break
d2 = int(rate / pow(2, (step * math.log(rate / delta, 2) - 1) / step))
delta = max(d2, delta + 1)
last_note = note
note = 12 * math.log(rate/delta)
# print "delta = %d, f = %d, note = %5.1f, diff = %5.1f" % (
# delta, rate/delta, note, last_note - note)
else:
print
print " Can't find pitch (2). Returning best guess."
print " start", start
print " maxr", maxr
print " maxt", maxt
print " minr", minr
print " mint", mint
print " delta", delta
print " latch", latch
# return 0
# if not _log_pitch:
# raise Exception("Sample too short (2)")
return wave.fmt.sampleRate / float(mint)
# find nth zero crossing (looking forward or backward)
#
# Note: only backwards has been used yet
def find_nth_zero(wave, start_sn, end_sn, slope=1, count=_lead_crossings):
if start_sn < end_sn:
first_sn = start_sn
last_sn = end_sn + 1
start_ix = 0
stop_ix = last_sn - first_sn
incr = 1
else:
first_sn = end_sn
last_sn = start_sn + 1
start_ix = last_sn - first_sn - 1
stop_ix = 0
slope = -slope
incr = -1
# read samples into buffer
samps = []
wave.seekSample(first_sn)
for sn in range(first_sn, last_sn):
samps.append(wave.readSample()[0])
last = samps[start_ix]
best = 0
for ix in range(start_ix + incr, stop_ix, incr):
this = samps[ix]
# print first_sn + ix, this ##################################
if last * slope < 0 and this * slope >= 0:
# print first_sn + ix, last, this, slope
count -= 1
best = first_sn + ix
if count == 0:
return(first_sn + ix)
last = this
if best != 0:
return best
if True:
print " start_sn ", start_sn
print " end_sn ", end_sn
print " slope ", slope
raise Exception("No zero crossing found with required slope")
# Find the end of the note.
#
# Return (end_sn, limit_sn, peak), where
# end_sn is sample number of the actual end of the note.
# limit_sn is the place to end the sample file.
# When the note exceeds _max_duration, limit_sn is less than end_sn.
# Otherwise, limit_sn exceeds end_sn, because it includes _dwell_t
# at the end of the note.
def find_end(wave, start_sn, noise, dwell_t, max_t):
calc_interval = wave.fmt.sampleRate / _calcs_per_sec
noise = max(noise, -60.0)
dwell_t = int(dwell_t * wave.fmt.sampleRate)
max_t = int(max_t * wave.fmt.sampleRate)
# print "### max_t =", jtime.sm(max_t, wave.fmt.sampleRate)
buf = jwave.Rmsbuf(wave, 0)
wave.seekSample(start_sn)
sn = 0
limit_sn = None
while True:
try:
buf.add(buf, wave.readSample()[0])
except IndexError:
print " Sample ends before silence"
return (start_sn + sn, buf.getPeak())
if sn % calc_interval == 0:
rms = buf.getRms()
if rms < noise:
end_sn = start_sn + sn
if limit_sn == None:
limit_sn = min(end_sn + dwell_t, wave.numSamples - 1)
return (end_sn, limit_sn, buf.getPeak())
if not limit_sn and sn > max_t:
limit_sn = buf.findPrevCrossing() + start_sn
# print "### found limit at", jtime.sm(limit_sn, wave.fmt.sampleRate)
sn += 1
raise Exception("Can't find sample end")
def copy_wave(iwave, start_sn, end_sn, file_num, freq, sn_ratio, peak, duration):
global _logfile
if freq == 0:
mnote = 0
notename = "X%02d" % file_num
cents = 0
else:
(mnote, notename, cents) = jmidi.midi_note_for_freq(freq)
fname = (
_folder
+ _fn_prefix
+ "%03d_" % mnote
+ notename
# + "_"
# + "%+03d_" % cents
# + "%07.2fHz_" % freq
# + "%03.0fdB_" % sn_ratio
# + jtime.sm(duration, iwave.fmt.sampleRate) + "s"
+ _fn_suffix
+ ".wav")
print "File %3d:" % file_num, fname
print >>_logfile, _fn_prefix \
,",", file_num \
,",", mnote \
,",", notename.strip("_") \
,",", "%+03d" % cents \
,",", "%7.2f" % freq \
,",", "%4.1f" % sn_ratio \
,",", "%4.1f" % peak \
,",", jtime.sm(duration, iwave.fmt.sampleRate) + "s"
if not _dry_run:
ofile = file(fname, "wb")
owave = jwave.WaveChunk(outf = ofile)
owave.copyHeader(iwave)
# owave.setNote(mnote)
owave.writeHeader(end_sn + 1 - start_sn)
owave.copySamples(iwave, start_sn, end_sn)
# find first zero crossing before trig_sn, where
# the difference bewteen two successive samples is less than
# twice the default noise level.
def find_start(wave, trig_sn, start_sn):
vbose = True
if vbose:
print " ",
# read channel 1 samples into buffer
samps = []
wave.seekSample(start_sn)
for sn in range(start_sn, trig_sn):
samps.append(wave.readSample()[0])
end_ix = len(samps) - 1
last = samps[end_ix]
noise = wave.dB2v(_default_noise) * 8
for ix in range(end_ix - 1, 0, -1):
this = samps[ix]
if -noise < this < noise:
if vbose:
print ".",
if abs(this - last) < noise:
if vbose:
print
return start_sn + ix
last = this
raise Exception("Can't find start of sample")
def old_find_start(wave, trig_sn, start_sn):
# read channel 1 samples into buffer
samps = []
wave.seekSample(start_sn)
for sn in range(start_sn, trig_sn):
samps.append(wave.readSample()[0])
# find N samples in a row whose values are less than default noise
N = 3
count = 0
start_ix = len(samps)
noise = wave.dB2v(_default_noise)
for ix in range(start_ix - 1, 0, -1):
# print "%6d %6d" % (ix, this)
if abs(samps[ix]) < noise:
# print ".",
count += 1
if count == N:
return start_sn + ix
else:
count = 0
raise Exception("Start of sample not found")
def process_samples():
global _default_noise
try:
inf = file(_infile, "rb")
except IOError, msg:
raise IOError(msg)
riff = jwave.RiffChunk(inf)
riff.readHeader()
riff.printHeader()
# if riff.type != "riff":
# print "Unsupported format (only wave files supported)"
# return 1
wave = jwave.WaveChunk(riff=riff, inf=inf)
wave.readHeader()
wave.printHeader()
rate = wave.fmt.sampleRate
if wave.fmt.compCode != 1:
print "Compressed formats unsupported"
sys.exit(1)
print
file_num = 1
end_sn = 1
while True:
t = jtime.start()
# 1) find the next peak that exceeds the trigger level
trig_sn = find_trigger(wave, end_sn, trig_dB=_trig_db)
if trig_sn == 0:
return ## EOF, we're done.
if _verbose:
print
print " trig_sn ", trig_sn, jtime.hmsm(trig_sn, rate)
# 2) Starting from the trigger point, search backwards to find the
# first positive sloped zero crossing. Search at most a fraction of a second.
end_sn = max(end_sn, trig_sn - rate/10)
# start_sn = find_nth_zero(wave, trig_sn, end_sn, slope=1)
start_sn = find_start(wave, trig_sn, end_sn)
start_sn = max(1, start_sn - int(_lead_time * rate))
if _verbose:
print " start_sn ", start_sn, jtime.hmsm(start_sn, rate)
# 3) Back up at most a second and measure a half-second of noise
noise_sn = max(1, start_sn - rate)
dur = min(rate / 2, (start_sn - noise_sn) / 2)
noise_lev = measure_rms(wave, noise_sn, dur)
if noise_lev == None:
print " Can't measure noise, using %5.2f dB" % _default_noise
noise_lev = _default_noise
else:
# use this value if we can't measure it later
_default_noise = noise_lev
if _verbose:
print " noise_lev ", noise_lev
# 4) Find where the sample ends:
# where the RMS level matches the initial noise level plus a delta,
# plus a dwell time.
(end_sn, limit_sn, peak_lev) = find_end(wave, trig_sn, noise_lev + _noise_delta,
_dwell_time, _max_duration)
sdur = limit_sn - start_sn
ndur = end_sn - start_sn
if _verbose:
print " end_sn ", end_sn, jtime.hmsm(end_sn, rate)
print " limit_sn ", limit_sn, jtime.hmsm(end_sn, rate)
print " note duration", jtime.sm(ndur, rate)
print " samp duration", jtime.sm(sdur, rate)
if ndur < _min_duration * wave.fmt.sampleRate:
if _verbose:
print " Skipping .. too short"
print
continue
# 5) Find which note the sample is
if _find_note:
freq = find_pitch(wave, trig_sn)
if _verbose:
print " freq ", freq
print
# 6) Record results & copy wave data
if _debug:
print
print "%3d freq: %-6.1f floor:%5.1f peak:%5.1f S/N: %-5.1f start:%d=%9s dur:%9s" % (
file_num,
freq,
noise_lev,
peak_lev,
peak_lev - noise_lev,
start_sn, jtime.msm(start_sn, rate),
jtime.msm(sdur, rate),
jtime.msm(ndur, rate),
)
copy_wave(wave, start_sn, limit_sn, file_num, freq, peak_lev - noise_lev, peak_lev, sdur)
file_num += 1
t = jtime.end(t)
print
print " Elapsed time:", jtime.msm(t, 1)
def usage(prog):
print >>sys.stderr
print >>sys.stderr, "%s: cut wave file into individual samples" % prog
print >>sys.stderr
print >>sys.stderr, " Usage: %s {[-f <outfolder>] {<wavefile>}}" % prog
print >>sys.stderr
print >>sys.stderr, "where:"
print >>sys.stderr, " { x } means 'any number of x'"
print >>sys.stderr, " -f <outfolder> specifies the output folder for"
print >>sys.stderr, " sample files for following input wave files."
print >>sys.stderr, " <wavefile> is a wave file containing mutliple"
print >>sys.stderr, " samples. Unix-style globbing is permitted,"
print >>sys.stderr, " that is, you can use '*.wav' or 'samp*/my*foo.wav'."
print >>sys.stderr
sys.exit(1)
def main(prog, args):
global _fn_prefix
global _fn_suffix
global _infile
global _folder
global _pitchlog
global _logfile
rCode = 0
if len(args) < 1:
usage(prog)
return 1
if _log_pitch:
print "OPENING PITCH LOG"
_pitchlog = open("pitch.csv", "w")
t1 = jtime.start()
file_count = 0
while len(args) > 0:
if len(args) > 2 and args[0] == "-f":
_folder = args[1] + "/"
print "Output folder:", args[1]
del args[0]
del args[0]
if len(args) < 1:
return rCode
fspec = args[0]
del args[0]
for _infile in glob.glob(fspec):
file_count += 1
print "\nProcessing", _infile, "==================================="
print
# Split the file name into prefix (inst name) and suffix (velocity)
basename = _infile.split(".")[0] # strip ".wav"
basename = jtrans.tr(basename, "\\", "/")
basename = basename.split("/")[-1] # strip path
parts = basename.split("_")
_fn_prefix = parts[0] + "_"
del parts[0]
_fn_suffix = "_" + "_".join(parts)
print "prefix =", _fn_prefix
print "suffix =", _fn_suffix
_logfile = open(_folder + _fn_prefix + _fn_suffix[1:] + "_log.csv", "w")
print >>_logfile, "fn_prefix" \
,",", "file_num" \
,",", "mnote" \
,",", "notename" \
,",", "cents" \
,",", "freq" \
,",", "sn_ratio" \
,",", "peak" \
,",", "duration"
t2 = jtime.start()
try:
if prof:
rCode = profile.run("process_samples()")
else:
rCode = process_samples()
except IOError, msg:
print msg
if len(args) > 0:
print "Skipping ..."
continue
print
print "Elapsed time for %s: " % _infile, jtime.hms(jtime.end(t2), 1)
_logfile.close()
if file_count > 1:
print
print "Elapsed time for all files:", jtime.hms(jtime.end(t1), 1)
return rCode
prof = False
if __name__ == "__main__":
warnings.filterwarnings("default", ".*")
# warnings.filterwarnings("error", ".*")
args = sys.argv
prog = args[0].split("\\")[-1]
del args[0]
# command line mode
rCode = main(prog, args)
sys.exit(rCode)
### Maybe later. Works but I don't like it.
while True:
print "Args: (^C to exit)",
try:
print
main(sys.stdin.readline())
print
except KeyboardInterrupt:
sys.exit(0)