-
Notifications
You must be signed in to change notification settings - Fork 2
/
TrioWaveCutter_v1.0_linux.py
344 lines (301 loc) · 12.1 KB
/
TrioWaveCutter_v1.0_linux.py
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
# -*- coding: utf-8 -*-
#!/usr/bin/env python3
# ++++++++++++++++++++++++++++++++++++++++++++
# IMPORTS
# ++++++++++++++++++++++++++++++++++++++++++++
import sys
import time
import os
import statistics as s
from glob import glob
import re
import operator
# ++++++++++++++++++++++++++++++++++++++++++++
# GLOBALS
# ++++++++++++++++++++++++++++++++++++++++++++
offsetAudio = 44 # bytes - 0...43 = header
chunkSize = 32768 #bytes
wavDir = 'Trio_wav_export'
fileExtension = '.wav'
sampleRate = 44100 # Hz
resolution = 16 # bit
headerFile = wavDir+'/header.bin'
#userArgs = sys.argv[1:] # everything but the script name
# # ++++++++++++++++++++++++++++++++++++++++++++
# # DEBUG?
# # ++++++++++++++++++++++++++++++++++++++++++++
debug = False
debugDir = 'debug'
# ++++++++++++++++++++++++++++++++++++++++++++
# FUNCTIONS
# ++++++++++++++++++++++++++++++++++++++++++++
# int.from_bytes(item, byteorder='little')
# for i in range(1300, 1319, 4):
# if not data[i:i + 4] == b'\x00' * 4:
# parts.append(data[i:i + 4])
# if buffer == b'\x00'*chunkSize:
def intro():
print('-----------------------------------------------------------------------------')
print('| @@ |')
print('| @@ |')
print('| @@@@@@@@ |')
print('| @@ |')
print('| @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@ @@@@@@@@@@@@@ @@ |')
print('| @@@ @@@ @@@ @@@ @@@@ @@@ |')
print('| @@@ @@@ @@@ @@@ @@@ @@@@ |')
print('| @@@ @@@ @@@ @@@ @@@@ @@@ |')
print('| @@@ @@@ @@@@ @@@ @@@ @@@@ |')
print('| @@@ @@@@@@@@@@@@@ @@@ @@@ @@@ |')
print('| @@@ @@@ @@@@ @@@ @@@ @@@ |')
print('| @@@ @@@ @@@ @@@ @@@ @@@ |')
print('| @@@ @@@ @@@ @@@ @@@@ @@@ |')
print('| @@@ @@@ @@@@ @@@ @@@@ @@@@@ |')
print('| @@@ @@@ @@@ @@@ @@@@@@@@@@ |')
print('-----------------------------------------------------------------------------')
print('WAVE CUTTING TOOL - giveabit@mail.ru\n\n')
time.sleep(0.5)
def init():
if not os.path.isdir(wavDir):
os.mkdir(wavDir)
fileList = glob('*'+ fileExtension)
if debug:
if not os.path.isdir(debugDir):
os.mkdir(debugDir)
return fileList
def readBytes(fileName, offset):
with open(fileName, 'rb') as f:
f.seek(offset)
buffer = f.read()
return buffer
def outFile(fileName, writeBytes):
with open(fileName,'ab') as f:
f.write(writeBytes)
return
def writeHeader(sizeAudio):
data = []
data.append('RIFF'.encode())
fileSize = sizeAudio+44-8 #file-fileSize (equals file-fileSize - 8); wav header = 44 bytes
sampleRate = 44100
numberChannels = 1
bitsPerSample = 16
byteRate = int(sampleRate*bitsPerSample*numberChannels/8)
blockAlign = int(numberChannels*bitsPerSample/8)
subChunk2Size = fileSize-44
data.append(fileSize.to_bytes(4,'little'))
data.append('WAVEfmt '.encode())
data.append((16).to_bytes(4,'little')) #Subchunk1Size 16 for PCM
data.append((1).to_bytes(2,'little')) #Type of format (1 is PCM)
data.append(numberChannels.to_bytes(2,'little')) #Number of Channels
data.append(sampleRate.to_bytes(4,'little')) #sample rate
data.append(byteRate.to_bytes(4,'little'))# byteRate = sample Rate * BitsPerSample * Channels/ 8
data.append(blockAlign.to_bytes(2,'little'))#BlockAlign= NumChannels * BitsPerSample/8
data.append(bitsPerSample.to_bytes(2,'little')) # BitsPerSample
data.append('data'.encode())
data.append(subChunk2Size.to_bytes(4,'little'))#data-block fileSize (equals file-fileSize - 44)
with open(headerFile, 'wb') as f:
for item in data:
f.write(item)
def reportProgress(position, total):
progress = float(position/total)*100
sys.stdout.write("progress: %.2f%% \r" % (progress))
sys.stdout.flush()
def timeToBytes(timeSec):
numBytes = int(round(timeSec*sampleRate*resolution/8, 0))
if numBytes % 2:
numBytes += 1
return numBytes
def bytesToTime(positionBytes):
timeMilliseconds = int(round(positionBytes*8/resolution/sampleRate*1000,0))
return timeMilliseconds
def meanLoudness(data, startBytes, endBytes):
step = int(resolution/8)
values = []
mean = 0
std = 0
for i in range(startBytes, endBytes, step):
temp = data[i:i+step]
val = int.from_bytes(temp, byteorder='little', signed=True)
if val > 0:
values.append(val)
else:
values.append(-1*val)
if len(values) > 1:
mean = int(s.mean(values))
std = int(s.stdev(values, mean))
# print(len(values))
return mean, std
def scanAudio(data, start, end):
start = end
lenght = timeToBytes(0.001)
end += lenght
starts = []
ends = []
audio = False
while not audio and not end > len(data):
if start % 10 == 0:
reportProgress(start, len(data))
# print('-', bytesToTime(start), bytesToTime(end))
meanTest, foo = meanLoudness(data, start, end)
if meanTest > cutOn:
audio = True
# input(audio)
starts.append(start-lenght)
out = '\t\t\t'+str(bytesToTime(start - lenght))+' ms\r'
sys.stdout.write(out)
start += lenght
end = start + lenght
else:
start += lenght
end = start + lenght
counter = 0
startOld = None
skipAhead = True
firstRun = True
while audio and not end > len(data):
if start % 10 == 0:
reportProgress(start, len(data))
# print('+', bytesToTime(start), bytesToTime(end))
meanTest, foo = meanLoudness(data, start, end)
if meanTest < cutOn:
if startOld:
if startOld + (counter + 1) * lenght == start:
counter += 1
skipAhead = False
else:
counter = 0
startOld = None
lastWhileSkipping = start
if firstRun:
skipAhead = True
else:
startOld = start
skipAhead = False
if counter == 1000:
# input('1000')
if firstRun:
# input('first')
# print(skipAhead)
firstRun = False
start = lastWhileSkipping
startOld = None
counter = 0
else:
audio = False
ends.append(startOld)
out = '\t\t\t' + str(bytesToTime(starts[-1]))+ ' ms \t...\t' + str(bytesToTime(startOld)) + ' ms\n'
sys.stdout.write(out)
if skipAhead:
start += 1000*lenght
end = start + lenght
else:
start += lenght
end = start + lenght
reportProgress(1,1)
return starts, ends
def writeRoutine(data, starts, ends, userArgs):
audio = zip(starts, ends)
sequence = []
instruments = {'g': 'guitar', 'b': 'bass', 'd': 'drums'}
for char in userArgs:
sequence.append(instruments[char])
counter = 0
counter2 = 0
for item in audio:
start, end = item
if counter + 1 > len(sequence):
counter = 0
counter2 += 1
outFileName = wavDir + '/' + fileName.split('.')[0] + '_' + sequence[counter] + '_' + str(counter2) + '.tmp'
outFile(outFileName, data[start:end + 2])
headerHandling(outFileName)
counter += 1
def headerHandling(outFileName):
try:
sizeAudio = os.path.getsize(outFileName) # we need the size to write a correct wav header
writeHeader(sizeAudio) # do it!
with open(headerFile, "ab") as f1, open(outFileName, "rb") as f2:
f1.write(f2.read()) # now pump the data at the end of the header
wavFile = outFileName[:-3] + 'wav'
if os.path.isfile(wavFile):
os.remove(wavFile)
os.rename(headerFile, wavFile) # rename nicely!
os.remove(outFileName) # and clean up ;-)
except:
print('\nWe encountered an error while processing: ' + outFileName)
e = sys.exc_info()[0]
print('The error message reads: ', e, '\n')
if os.path.isfile(outFileName):
os.remove(outFileName)
def userArgsHandling():
loop = True
print('What instruments have you recorded?')
print('You can input [g] for guitar, [b] for bass and [d] for drums.\n')
print('Please input the instruments in the order that they were recorded.')
print('If you enter nothing, \'gbd\' will be selected as default.')
while loop:
print('\n')
instrumentsNew = ''
instrDict = {'g': -1, 'b': -1, 'd': -1}
instruments = input('Your instruments are: ')
instruments = instruments.lower()
ex = re.compile('g')
result = ex.search(instruments)
if result:
pos, foo = result.span()
instrDict['g'] = pos
ex = re.compile('b')
result = ex.search(instruments)
if result:
pos, foo = result.span()
instrDict['b'] = pos
ex = re.compile('d')
result = ex.search(instruments)
if result:
pos, foo = result.span()
instrDict['d'] = pos
sorted_instruments = sorted(instrDict.items(), key=operator.itemgetter(1))
for item, check in sorted_instruments:
if not check == -1:
instrumentsNew += item
if not instrumentsNew:
instrumentsNew = 'gbd'
print('Your choice was: '+instrumentsNew)
ok = input('correct? [y]/n: ')
default = 'y'
ok = ok or default
if ok.lower() in ['y','yes','1']:
loop = False
return instrumentsNew
# ++++++++++++++++++++++++++++++++++++++++++++
# M A I N
# ++++++++++++++++++++++++++++++++++++++++++++
intro()
fileList = init()
filesTotal = str(len(fileList))
nowTotal = time.time()
for fileName in fileList:
print('\nprocessing: '+fileName+'\n')
userArgs = userArgsHandling()
now = time.time()
data = readBytes(fileName, offsetAudio)
if debug:
debugFile = debugDir+'/'+fileName+'.DBG.txt'
else:
debugFile = None
sys.stdout.write('\n\t\t\t[x] gathering noise floor.')
start = timeToBytes(0)
end = timeToBytes(2)
meanFloor, stdFloor = meanLoudness(data, start, end)
cutOn = meanFloor + 4*stdFloor
cutOff = meanFloor # must not be negative !!!
sys.stdout.write('\n\t\t\t[x] scanning file.\n\n')
starts, ends = scanAudio(data, start, end)
if len(ends) < len(starts):
ends.append(len(data))
sys.stdout.write('\n\t\t\t[x] writing files.')
writeRoutine(data, starts, ends, userArgs)
runningTime = str(round(time.time()-now,1))+' seconds.\n'
sys.stdout.write('\n\t\t\t[x] finished in: '+runningTime)
runningTimeTotal = str(round(time.time()-nowTotal, 1))+' seconds.\n'
sys.stdout.write('\n'+filesTotal+' files overall processed in: '+runningTimeTotal)
input('<ENTER>')