-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtermProject.py
1602 lines (1531 loc) · 70 KB
/
termProject.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
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
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import pygame, pyaudio, wave, struct, random
import numpy as np
import math, os, threading
from queue import Queue
################################################################################
#15-112 Term Project
#Yuyi Shen, AndrewId: yuyis1, Section N
################################################################################
################################################################################
#Audio Processing section
################################################################################
#http://www.cs.cmu.edu/~112/notes/hw1.html
def almostEquals(x,y,epsilon=10**(-8)):
return (abs(x-y)<epsilon)
class audioHandler(object):
#Audio handling class
def __init__(self,path):
#Init audioHandler with wave file object and number of frames to read
self.wavFile=wave.open(path,'rb') #Use wave module to open .wav file
self.CHUNK=self.wavFile.getframerate()
self.sampWidth=self.wavFile.getsampwidth()
def readWavFile(self,dataCHUNK=None,stream=None):
#Read 1 sec of audio frames from given wave file and return as np array
if dataCHUNK==None: dataCHUNK=self.CHUNK
audioSamples=[]
fullData=b''
for frame in range(dataCHUNK):
#unpack data 1 frame at a time
audioData=self.wavFile.readframes(1)
fullData+=audioData
#Provide option to play audio on speaker
if stream!=None: stream.write(audioData)
if len(audioData)>0: #Make sure a frame is read
#Audio frames store data as short, signed ints
data=struct.unpack("%dh" % self.sampWidth, audioData)
audioSamples.append(int(data[0]))
else: return []
return np.array(audioSamples),fullData
def zeroPadAudio(audioData,windowCenter,factor):
#Implement zero-phase window zero padding
#Numpy fft is optimized for N=power of 2
N=len(audioData)
nextPowerOfTwo=2**(math.ceil(math.log(factor+N,2)))
audioData=(audioData[windowCenter:]+[0]*(factor)+
[0]*(nextPowerOfTwo-factor-N)+
audioData[:windowCenter])
return audioData
def besselFun(x,N,meshSize):
#Returns zeroth order modified bessel fun() of x
#(of first kind)
#Io(x)=(1/pi)*integral(e**(xcos(theta))dtheta) from 0 to pi
#Io(x)=(1/pi)*integral((1/root(1-u**2))*e^(-xu)) from -1 to 1
besselDeriv=lambda t,u:math.e**(-t*u)/((1-u**2)**0.5)
#Numerically integrate w/ double exponential transformation
thetaValue=lambda t:math.tanh(math.pi*0.5*math.sinh(t))
dThetaValue=lambda t:((1-math.tanh(math.pi*0.5*math.sinh(t))**2)*
math.pi*0.5*math.cosh(t))
fn=lambda t,u: besselDeriv(t,thetaValue(u))*dThetaValue(u)
lowerLim,upperLim,sample,meshSize,integral=-N,N,-N,meshSize,0
#Trapezoid rule
while (sample<upperLim):
try:
trapArea=meshSize*(fn(x,sample)+fn(x,sample+meshSize))/2
integral+=trapArea
sample+=meshSize
except:
#Catch zero division error (arg of fn decays to -1,1 very quickly)
sample+=meshSize
continue
return integral/math.pi
def kaiserWindow(n,windowLength,windowShape,windowRightShift=0):
#Window function for short time fourier transform
n-=windowRightShift #Account for window shift
lowerThreshold=0
#Center of window is 0.5 windowLength
upperThreshold=(windowLength-1)
#Increase windowShape for narrower window
alpha=windowShape
if n>upperThreshold or n<lowerThreshold:
return 0
else:
besselMesh=0.1 #meshSize for trapezoid rule (decrease for accuracy)
besselN=3.2
upperArg=math.pi*alpha*((1-(2*n/(upperThreshold)-1)**2)**0.5)
lowerArg=math.pi*alpha
return (besselFun(upperArg,besselN,besselMesh)/
besselFun(lowerArg,besselN,besselMesh))
def multDataByKaiserWin(data,kaiserShift,winBeta,winWidth,zeroThreshold=0.05):
#Apply kaiser window to audio data
#Approximate Kaiser window with step function to ease computation
totalWin=len(data)
steps=50
N=int(winWidth/steps)
pointer=0
kaiserVal=0
fftSample=[]
for i in range(0,totalWin):
if i%N==0:
kaiserVal=kaiserWindow(i+N/2,winWidth,winBeta,kaiserShift)
if kaiserVal<zeroThreshold:
kaiserVal=0
fftSample.append(data[i]*kaiserVal)
return fftSample
def shortTimeFourier(data,samplingFreq):
#Short time fourier transform function
#Assume music is played at 400 bpm max
#0.15 sec per beat
beatTime=0.15 #sec
beatLength=math.ceil(samplingFreq*beatTime) #Get number of samples per beat
#minFFTWindow is kaiser window width, each window represents 0.15 sec
minFFTWindow=int(beatLength) #In number of samples
sampleSpacing,totalWindow=1/samplingFreq,len(data)
originalWindowCenter=int(minFFTWindow/2)
windowBeta=5 #narrow window
fftFreqs=[]
#Overlap for windows will be 50%
windowShift=int(0.5*minFFTWindow)
shortTimeFT=[]
#i is window right shift
for i in range(0,totalWindow-windowShift,windowShift):
#Window the audio data with the Kaiser window
fftSample=multDataByKaiserWin(data,i,windowBeta,minFFTWindow)
windowCenter=originalWindowCenter+i
factor=10
#Zero pad the windowed data (zero phase to eliminate phase shift)
zeroPadFactor=((factor*minFFTWindow)-minFFTWindow-
(totalWindow-minFFTWindow))
fftSample=zeroPadAudio(fftSample,windowCenter,zeroPadFactor)
if len(fftFreqs)==0:
fftFreqs=np.fft.fftfreq(len(fftSample),sampleSpacing)
shortTimeFT.append(np.fft.rfft(fftSample))
return (fftFreqs,shortTimeFT,minFFTWindow,windowShift)
def movingAverage(L,averagePoints):
#compute symmetric moving average of L
mid=averagePoints//2
averageL=np.zeros((len(L),))
for i in range(len(L)):
avgSum=0
pointNum=0
for j in range(mid+1):
if j==0 or (i+j)<len(L):
avgSum+=L[i+j]
pointNum+=1
if j!=0 and (i-j)>=0:
avgSum+=L[i-j]
pointNum+=1
averageL[i]=avgSum/pointNum
return averageL
def stats(L):
#returns mean and standard deviation of L
mean=np.sum(L)/len(L)
residsSquared=(L-mean)**2
meanResidsSquared=np.sum(residsSquared)/len(residsSquared)
std=meanResidsSquared**0.5
return (mean,std)
def diffsBtwnAdjacentVals(L):
#Calculates average diff btwn adjacent values in L and standard dev.
numberOfDiffs=len(L)-1
differences=np.zeros((numberOfDiffs,))
for i in range(len(L)):
if (i+1)<len(L):
difference=abs(L[i+1]-L[i])
differences[i]=difference
return stats(differences)
def checkIfBlockContainsMaxima(L,N,i,threshold):
#Check if a block within list L starting at index i with length N contains
#a local maximum
currentBlock,nextBlock,previousBlock=L[i:i+N],L[i+N:i+2*N],L[i-N:i]
currentMean=np.sum(currentBlock)/len(currentBlock)
nextMean=np.sum(nextBlock)/len(nextBlock)
previousMean=np.sum(previousBlock)/len(previousBlock)
nextDiff,prevDiff=nextMean-currentMean,currentMean-previousMean
return ((prevDiff>0) and (nextDiff<0) and (abs(nextDiff)>threshold) and
(abs(prevDiff)>threshold))
def coarseScan(L,N):
#Coarse scans through list for local maxima, returns indices suspected
#of harboring maxima within N indices
suspectIndices=[]
threshold=0 #Noise threshold
for i in range(1,len(L),N):
if (i+2*N)<=len(L) and (i-2*N)>=0:
if checkIfBlockContainsMaxima(L,N,i,threshold):
suspectIndices.append(i)
elif (i-2*N)>=0 and (i+2*N)>len(L): #Boundary condition
#If block being checked is too close to end of list L...
currentBlock,previousBlock=L[i:i+N],L[i-N:i]
currentMean=np.sum(currentBlock)/len(currentBlock)
previousMean=np.sum(previousBlock)/len(previousBlock)
diff=currentMean-previousMean
if diff>0 and diff>threshold: suspectIndices.append(i)
elif (i+2*N)<=len(L) and (i-2*N)<0: #Boundary condition
#If block being checked is too close to beginning of list L
currentBlock,nextBlock=L[i:i+N],L[i+N:i+2*N]
currentMean=np.sum(currentBlock)/len(currentBlock)
nextMean=np.sum(nextBlock)/len(nextBlock)
if (nextMean<currentMean) and (currentMean-nextMean)>threshold:
suspectIndices.append(i)
else: print("Error. Enter a smaller N")
return suspectIndices
def fineScan(L,suspectIndices,N,meanMagnitude,magnitudeSTD,stds):
#Returns indices associated with peak values in L
#noiseFloor is minimum value for data to not be considered noise
maximumIndices,noiseFloor=[],meanMagnitude+stds*magnitudeSTD
for i in suspectIndices:
#For each block in L starting at an index in suspectIndices, go through
#N indices from that index and look for a peak
for j in range(N):
index=i+j
if index<len(L):
currentVal=L[index]
if index-1<0:
#If current index is 0...
nextVal=L[index+1]
if (currentVal-nextVal)>0 and L[index]>noiseFloor:
maximumIndices.append(index)
elif index+1>=len(L):
#If current index is -1...
prevVal=L[index-1]
if (currentVal-prevVal)>0 and L[index]>noiseFloor:
maximumIndices.append(index)
else:
prevVal,nextVal=L[index-1],L[index+1]
if ((currentVal>prevVal) and (currentVal>nextVal) and
L[index]>noiseFloor):
maximumIndices.append(index)
return maximumIndices
def fftPeakDetector(fftFreqs,FFTresults):
#Detects peaks in FFT results
magnitude=np.absolute(FFTresults)
(meanMag,magSTD)=stats(magnitude)
phase=np.angle(FFTresults)
peaks=[]
#Smooth the FFT data
smoothingFactor=0.05 #percent
percentConversionFactor=0.01
averagePoints=int(len(magnitude)*percentConversionFactor*smoothingFactor)
smoothed=movingAverage(magnitude,averagePoints)
(meanDiff,std)=diffsBtwnAdjacentVals(smoothed)
#Set coarse scan to use blocks of size 10. Set fine scan to use noise
#threshold of 2 standard deviations
N,noiseThresh=10,2
suspectIndices=coarseScan(smoothed,N)
suspectFreqs=fftFreqs[suspectIndices,]
smoothedMags=smoothed[suspectIndices,]
maximaIndices=fineScan(smoothed,suspectIndices,N,meanMag,magSTD,noiseThresh)
maximaFreqs=fftFreqs[maximaIndices,]
maxMags=magnitude[maximaIndices,]
maxPhases=phase[maximaIndices,]
#Return values associated with max indices
return (maximaIndices,maximaFreqs,maxMags,maxPhases)
def coarseDiffScanner(val,L,N):
#Goes through blocks of L, finds block with mean closest to val
bestDiff=None
bestIndex=None
for i in range(0,len(L),N):
block=L[i:i+N]
mean=np.sum(block)/N
diff=abs(mean-val)
if bestDiff==None or diff<bestDiff:
bestDiff=diff
bestIndex=i
return bestIndex
def fineDiffScanner(val,L,startIndex,N,tolerableFreqDeviation):
#Returns index of value in L closest to val
maxIndex=len(L)
try:
for i in range(startIndex,startIndex+N):
if i<maxIndex:
freq=L[i]
if abs(freq-val)<tolerableFreqDeviation:
return i
else: break
return None
except:
print("ERROR")
class guideObject(object):
#guide objects for peak continuation algorithm
def __init__(self,freq,mag,phase,asleep=False,time=0):
self.freq=freq
self.mag=mag
self.phase=phase
self.asleep=False
self.timeSpentAsleep=time
def get(self):
return (self.freq,self.mag,self.phase,self.asleep,self.timeSpentAsleep)
def deleteIndicesFromLists(L,i):
#Delete the elements at index i from each list in L
newLists=[]
for j in range(len(L)):
listForDeletion=L[j]
np.delete(listForDeletion,[i])
newLists.append(listForDeletion)
return tuple(newLists)
def peakContinuation(freqs,STFTdata):
#Generate guides through peak continuation algorithm from STFT data
#Each guide object contains freq,mag,phase info on the period of time it
#corresponds to.
guides,guideCounter=[],0
for i in range(len(STFTdata)-1,-1,-1):
#Go backwards
(indices,maxFreqs,maxMags,maxPhases)=fftPeakDetector(freqs,STFTdata[i])
guideDict=dict()
if len(guides)==0:
for j in range(len(indices)):
newKey="g"+str(guideCounter)
guideCounter+=1
guideDict[newKey]=guideObject(maxFreqs[j],maxMags[j],
maxPhases[j])
else:
prevGuide=guides[0]
for guide in prevGuide:
(freq,mag,phase,sleep,timeAsleep),N=prevGuide[guide].get(),3
if len(maxFreqs)>0:
nearInd,freqDev=coarseDiffScanner(freq,maxFreqs,N),10 #hertz
nearestInd=fineDiffScanner(freq,maxFreqs,nearInd,N,freqDev)
else: nearestInd=None
if nearestInd!=None:
(newFreq,newMag,newPhase)=(maxFreqs[nearestInd],
maxMags[nearestInd],
maxPhases[nearestInd])
lists=[indices,maxFreqs,maxMags,maxPhases]
(indices,maxFreqs,maxMags,maxPhases)=deleteIndicesFromLists(
lists,nearestInd)
guideDict[guide]=guideObject(newFreq,newMag,newPhase)
else:
maxTimeAsleep=3
if timeAsleep<maxTimeAsleep:
guideDict[guide]=guideObject(freq,mag,phase,
True,timeAsleep+1)
for j in range(len(indices)):
newKey="g"+str(guideCounter)
guideCounter+=1
guideDict[newKey]=guideObject(maxFreqs[j],
maxMags[j],maxPhases[j])
guides=[guideDict]+guides
return guides
def calculateSMSFun(guideDict,t):
#Calculate approximate audio value from SMS (sinusoidal) model of audio
result=0
for guides in guideDict:
#For each guideObject corresponding to time t...
guide=guideDict[guides]
if not guide.asleep:
(freq,mag,phase,sleep,timeSleeping)=guide.get()
angularFreq=2*math.pi*freq
#Compute the value of the frequency component described by the guide
component=(mag*math.cos(angularFreq*t+phase))
result+=component
return result
def generateModeledAudioData(SMSguides,STFTframeShift,STFTWinWidth,data):
#Generate sinusoidal model of audio data
dataLen,maxData=len(data),np.max(data)
#Init numpy array same size as audio data being modeled
SMSmodel=np.zeros(dataLen,)
for i in range(len(SMSguides)):
#Each guideDict in SMSguides corresponds to a block in time. startDataI
#is the index corresponding to the start of that block.
startDataI=i*STFTframeShift
guideDict=SMSguides[i]
if i==0: #Account for boundary conditions
for j in range(STFTframeShift):
SMSmodel[j]=calculateSMSFun(guideDict,j)
nextGuideDict=SMSguides[i+1]
for j in range(STFTframeShift,STFTWinWidth):
#Guide dict time blocks overlap by 50%, therefore compute AVG
#of guide dict functions during this overlap
SMSmodel[j]=(calculateSMSFun(guideDict,j)+
calculateSMSFun(nextGuideDict,j))/2
elif i==(len(SMSguides)-1): #boundary condition
prevGuideDict=SMSguides[i-1]
for j in range(startDataI,startDataI+STFTframeShift):
SMSmodel[j]=(calculateSMSFun(guideDict,j)+
calculateSMSFun(prevGuideDict,j))/2
for j in range(startDataI+STFTframeShift,startDataI+STFTWinWidth):
if j>=dataLen: break
SMSmodel[j]=calculateSMSFun(guideDict,j)
else:
prevGuideDict,nextGuideDict=SMSguides[i-1],SMSguides[i+1]
for j in range(startDataI,startDataI+STFTWinWidth):
if j<(startDataI+STFTframeShift):
SMSmodel[j]=(calculateSMSFun(guideDict,j)+
calculateSMSFun(prevGuideDict,j))/2
else:
SMSmodel[j]=(calculateSMSFun(guideDict,j)+
calculateSMSFun(nextGuideDict,j))/2
#Calculate last index covered by Sinusoidal modeling of audio data
endI=(len(SMSguides)-1)*STFTframeShift+STFTWinWidth
#If any remaining empty spots in SMSmodel array, fill with values from
#function in the last dictionary of guides
finalGuideDict=SMSguides[-1]
for i in range(endI,dataLen):
SMSmodel[i]=calculateSMSFun(finalGuideDict,i)
#Scale the SMS array to the actual audio data
maxSMS=np.max(SMSmodel)
scalingFactor=maxData/maxSMS
return SMSmodel*scalingFactor
def peakDetectorFilter(L,N):
#Envelope detector (NOT TO BE CONFUSED with local maxima)
shift=int(N/2)
envelope=np.zeros(len(L),)
for i in range(len(L)):
if (i-shift)>=0:
peak=np.max(L[i-shift:i+shift])
else:
peak=np.max(L[:i+shift])
envelope[i]=peak
return envelope
def butterWorthGain(freq,fc,DCgain,order):
#Low pass filter gain
gain=DCgain/((1+(freq/fc)**(2*order))**0.5)
return gain
def butterWorthFilter(signal,sampleRate,order,DCgain):
#Low pass filter
scalingFactor=0.0002
fc=scalingFactor*sampleRate
fftSig=np.fft.rfft(signal)
filteredSig=[]
sampleSpacing=1/sampleRate
fftFreqs=np.fft.fftfreq(len(signal),sampleSpacing)
for i in range(len(fftSig)):
nextPoint=fftSig[i]*butterWorthGain(fftFreqs[i],fc,DCgain,order)
filteredSig.append(nextPoint)
smoothingPoints=200
filteredSig=np.array(filteredSig)
return movingAverage(np.fft.irfft(filteredSig),smoothingPoints)
#http://www.cs.cmu.edu/~112/notes/notes-strings.html
def readFile(path):
with open(path, "rt") as f:
return f.readlines()
def writeFile(path, contents):
with open(path, "wt") as f:
f.write(contents)
def appendFile(path, contents):
with open(path, "a") as f:
f.write(contents)
def findPeakResidualIndices(data,samplingFreq):
#Take in array of audiodata, model it with a sum of sinusoids, calculate
#error in the model, find peaks in error, and return indices of those peaks
envSmoothing=60
#Compute short time Fourier transform (STFT)
(fftfreq,STFT,STFTWinWidth,winShift)=shortTimeFourier(data,samplingFreq)
#Generate guides containing magnitude, freq, phase info from STFT
guides=peakContinuation(fftfreq,STFT)
#Calculate audio data values using guide info as a model
SMSmodel=generateModeledAudioData(guides,winShift,STFTWinWidth,data)
#Calculate error by subtracting SMSmodel from actual audio data.
filteredResids=peakDetectorFilter(np.absolute(data-SMSmodel),envSmoothing)
lowPassResids=butterWorthFilter(filteredResids,samplingFreq,1,1)
N=10
(mean,std)=stats(lowPassResids)
#Find error peaks and return their indices
nearPeakIndices=coarseScan(lowPassResids,N)
noiseThresh=1.2
peakIndices=fineScan(lowPassResids,nearPeakIndices,N,mean,std,noiseThresh)
return peakIndices
def writeMusicResidualsToFile(targetFile,audioFile):
#Take in audio file, calculate SMS model of audio, calculate error, write
#error to targetFile
writeFile(targetFile,"") #Wipe file
audioReader=audioHandler(audioFile)
samplingFreq=audioReader.wavFile.getframerate()
#Write audio file name to target file
appendFile(targetFile,str(audioFile)+'\n')
#Read new audio data from audioFile
data=audioReader.readWavFile()[0]
audioFramesRead,sampleSpacing,counter=audioReader.CHUNK,1/samplingFreq,0
while len(data)>0:
#Find the indices associated with peaks in the error in the SMS model
peakIndices=findPeakResidualIndices(data,samplingFreq)
for i in peakIndices:
#Calculate the time associated with each error peak
timeStampWithinWindow=i*sampleSpacing
startTime=counter*audioFramesRead*sampleSpacing #sec
timeStamp=startTime+timeStampWithinWindow
(dataMean,dataSTD)=stats(data)
dataVal=data[i]
#If the audio volume is high, add the timeStamp to targetFile
if dataVal>(dataMean+dataSTD):
peakString=(str(timeStamp)+","+str(dataVal)+","+
str(dataMean)+","+str(dataSTD)+"\n")
appendFile(targetFile,peakString)
counter+=1
data=audioReader.readWavFile()[0]
################################################################################
#Audio thread classes
################################################################################
class audioPlayer(threading.Thread):
#Audio player class for game
def __init__(self,queue,output,stream):
#Inits a thread
threading.Thread.__init__(self)
self.queue=queue
self.output=output
self.stream=stream
self.isRunning=True
self.paused=False
self.pauseCondition=threading.Condition(threading.Lock())
self.chunk=1024
self.silence=chr(0)*self.stream._channels*2
self.stopped=False
def run(self):
#While thread is running, takes in audio data from self.queue, plays it,
#and writes it to the output queue
while self.isRunning:
with self.pauseCondition: #If thread paused, wait.
while self.paused:
self.pauseCondition.wait()
if self.queue.empty():
continue
if self.output.qsize()>0:
self.output.get()
#Update output queue with latest data being played
(numpyInfo,data)=self.queue.get()
self.output.put(numpyInfo)
self.stream.write(data)
free=self.stream.get_write_available()
if free>self.chunk:
self.stream.write(self.silence*(free-self.chunk))
self.queue.task_done()
self.stopped=True
def stop(self): #Stop the thread
self.isRunning=False
def pause(self): #Pause the thread
self.paused=True
self.pauseCondition.acquire()
def resume(self): #Resume the thread
self.paused=False
self.pauseCondition.notify()
self.pauseCondition.release()
class audioProcessor(threading.Thread):
#Audio processing class for loading new wav files
def __init__(self,queue,textFile):
threading.Thread.__init__(self)
self.queue=queue
self.textFile=textFile
self.isRunning=True
def run(self):
while self.isRunning:
#While thread is running, get a new audio file and process it.
newAudioFile=self.queue.get()
writeMusicResidualsToFile(self.textFile,newAudioFile)
self.queue.task_done()
self.stop()
def stop(self):
self.isRunning=False
################################################################################
#File processing
################################################################################
def almostIn(n,L,epsilon=0.05):
#Checks if n is within epsilon of any elements in L
for entry in L:
if abs(entry-n)<epsilon:
return (True,entry)
return (False,None)
def removeSimilarEntries(path):
#Opens up 'beats.txt' file, removes beat entries that are too close together
textFile=open(path,'r')
fileLines=textFile.readlines()
textFile.close()
writeFile(path,"") #Clear file
appendFile(path,fileLines.pop(0)) #First line is audio file title
encounteredTimeStamps=[]
for lines in fileLines:
timeStamp=float(lines.split(',')[0])
if not almostIn(timeStamp,encounteredTimeStamps)[0]:
encounteredTimeStamps.append(timeStamp)
appendFile(path,lines)
################################################################################
#Graphics
################################################################################
def findMaxesOfList(L,numberOfMaxes): #For complex numbers
#Goes through list of complex numbers, finds n=numberOfMaxes numbers with
#largest magnitudes
maxNumbers=[]
absL=np.absolute(L) #Find list of magnitudes of complex numbers in L
for i in range(numberOfMaxes):
maxIndex=np.nonzero(absL==max(absL))[0][0]
maximum=L[maxIndex]
maxNumbers.append(maxIndex)
L=np.delete(L,maxIndex)
absL=np.delete(absL,maxIndex)
return maxNumbers
def mapListToMax(L,maximumValAllowed):
#Scales values in L to maximumValAllowed
scalingFactor=maximumValAllowed/np.max(L)
return L*scalingFactor
class Slider(object):
#DIY slider widget in pygame
def initSliderBar(self,pygameSurface,x,y):
#Initializes slider bar
self.barX=x
self.barY=y
barHeightScaling,barWidthScaling=0.75,0.05
self.barHeight=pygameSurface.get_height()*barHeightScaling
self.barWidth=pygameSurface.get_width()*barWidthScaling
self.barColor=(155,230,230)
self.barRect=(self.barX,self.barY,self.barWidth,
self.barHeight)
def initSlider(self,pygameSurface):
#Initializes slider position and dimensions
self.sliderNumber=0 #0-20
self.sliderMax=20
heightScaling,widthScaling=0.025,0.1
self.sliderHeight=pygameSurface.get_height()*heightScaling
self.sliderWidth=pygameSurface.get_width()*widthScaling
self.sliderColor=(245,0,87)
self.sliderX=(self.barX+self.barWidth/2)-self.sliderWidth/2
self.sliderMaxY=(self.barHeight+self.barY)-self.sliderHeight/2
self.sliderMinY=self.barY-self.sliderHeight/2
self.sliderRange=self.sliderMaxY-self.sliderMinY
self.sliderY=self.sliderMaxY
self.sliderRect=(self.sliderX,self.sliderY,self.sliderWidth
,self.sliderHeight)
def __init__(self,pygameSurface,surfaceX,surfaceY,x,y):
self.clicked=False
self.sliderSurface=pygameSurface
self.surfaceX,self.surfaceY=surfaceX,surfaceY
#Set slider bar attributes
self.initSliderBar(pygameSurface,x,y)
#Init slider
self.initSlider(pygameSurface)
#Init bounding box
(self.boxWidth,self.boxHeight)=(self.sliderWidth,
self.barHeight+
self.sliderHeight)
self.boxX,self.boxY=(self.sliderX),(self.barY-self.sliderHeight/2)
self.boxColor=(100,200,230)
self.box=(self.boxX,self.boxY,self.boxWidth,self.boxHeight)
def drawSlider(self,surface):
#Draw the slider object on surface
pygame.draw.rect(surface,self.boxColor,self.box)
pygame.draw.rect(surface,self.barColor,self.barRect)
pygame.draw.rect(surface,self.sliderColor,self.sliderRect)
def changeSliderPosition(self,newY):
#Change slider widget position to newY
newY=newY-self.surfaceY
if newY>self.sliderMaxY:
#If newY is too low, set slider to lowest position
self.sliderY=self.sliderMaxY
self.sliderNumber=0
elif newY<self.sliderMinY:
#If newY is too high, set slider to highest position
self.sliderY=self.sliderMinY
self.sliderNumber=self.sliderMax
else:
#Compute new slider number for slider position
self.sliderY=newY
self.sliderNumber=(self.sliderMax*(self.sliderMaxY-
(newY+self.sliderHeight/2))/self.sliderRange)
self.sliderRect=(self.sliderX,self.sliderY,self.sliderWidth
,self.sliderHeight)
def checkIfClickedOn(self,mouseX,mouseY):
#Check if slider has been clicked on
mouseX=mouseX-self.surfaceX
mouseY=mouseY-self.surfaceY
if mouseX>self.sliderX and mouseX<(self.sliderX+self.sliderWidth):
if mouseY>self.sliderY and mouseY<(self.sliderY+self.sliderHeight):
return True
return False
class fourierPad(object):
#Primary game objects (bubbles to be popped)
def __init__(self,x,y,r,freqs,mags,phases,sliders,
clicked=False,active=True,dying=False):
self.dying=dying
self.active=active
self.clicked=clicked
self.x=x
self.y=y
self.cy=y #y oscillates around cy
self.r=r
self.maxAmps=20 #Amplitudes of frequency components are at most 20
self.freqs=freqs
self.mags=[]
#Scale magnitudes to a max of 20
maxMags=max(mags)
for mag in mags:
self.mags.append(mag*self.maxAmps/maxMags)
self.phases=phases
self.sliders=sliders
#Calculate maximum possible error for player
self.maxError=sum([max(self.mags[i],self.maxAmps-self.mags[i])
for i in range(len(self.mags))])
#Generate coordinate list to be drawn
self.audioWaveFormCoords=self.generateWaveFormPoints()
self.playerCoords=self.generatePlayerPoints()
def scorePlayer(self):
#Gives the player a score
error=0
for i in range(len(self.sliders)):
error+=abs(self.sliders[i].sliderNumber-self.mags[i])
scorePercentage=1-error/self.maxError
lowScore,intermediateScore,highScore=10,50,100
zeroThreshold,lowThreshold,mediumThreshold=0.3,0.7,0.9
if scorePercentage<zeroThreshold:
return 0
elif scorePercentage<lowThreshold:
return lowScore
elif scorePercentage<mediumThreshold:
return intermediateScore
else:
return highScore
def checkIfClickedOn(self,mouseX,mouseY,gameScreenX,gameScreenY):
#Check if pad has been clicked on
mouseX-=gameScreenX
mouseY-=gameScreenY
distance=((mouseX-self.x)**2+(mouseY-self.y)**2)**0.5
#Use distance formula to check distance btwn mouse click and pad center
if distance<self.r:
return True
return False
def waveFormFunction(self,t):
#Calculates the value of the pad's waveform as a function of t
result=0
for i in range(len(self.freqs)):
angular=2*math.pi*self.freqs[i]
result+=self.mags[i]*math.cos(angular*t+self.phases[i])
return result
def playerFunction(self,t):
#Calculates the value of the player waveform as a function of t
result=0
for i in range(len(self.freqs)):
mag=self.sliders[i].sliderNumber
angular=2*math.pi*self.freqs[i]
result+=mag*math.cos(angular*t+self.phases[i])
return result
def generateWaveFormPoints(self,isPlayer=False):
#Generate pygame coordinates for fourier pad waveforms
coordinates,t,step,maxPercentOfR=[],0,0.03,0.2
periodsToGraph=8
while t<2*math.pi:
#Generate coordinates for four periods of the waveform
freq=min(self.freqs)
period=1/freq
if not isPlayer:
#Generate coordinates for pad waveform
result=self.waveFormFunction(t*periodsToGraph*
period/(2*math.pi))
else:
#Generate coordinates for player waveform
result=self.playerFunction(t*periodsToGraph*period/(2*math.pi))
scalingFactor=self.r*maxPercentOfR/(len(self.freqs)*self.maxAmps)
#Map waveform function value to radius of circular parametric
#function.
radius=self.r-result*scalingFactor
x=radius*math.cos(t)+self.x
y=-radius*math.sin(t)+self.y
coordinates.append((x,y))
t+=step
return np.array(coordinates)
def generatePlayerPoints(self):
#Generate coordinates for player waveform
return self.generateWaveFormPoints(True)
def drawHighlight(self,gameSurface,highlightColor,width):
#If the pad has been clicked on, highlight it
pygame.draw.lines(gameSurface,highlightColor,
True,self.audioWaveFormCoords,width)
pygame.draw.lines(gameSurface,highlightColor,
True,self.playerCoords,width)
def generatePadColors(self):
#Generate the colors of the bubble
highlightColor=(255,235,59)
baseColor=(90,255,100)
playerScore=self.scorePlayer()
fullG=255
fullScore=100
G=int(playerScore*fullG/fullScore)
playerColor=list(baseColor) #playerColor is color of player waveform
playerColor[1]=G
playerColor=tuple(playerColor)
padColor=(245,0,87) #padColor is color of pad audio waveform
return (padColor,playerColor,highlightColor)
def drawPad(self,gameSurface):
#Draw fourier pad as bubble
if not self.dying:
#If bubble has not popped
if self.checkIfSlidersClicked():
#If the fourier pad's sliders are being moved, update the
#player waveform coordinates
playerCoords=self.generatePlayerPoints()
self.playerCoords=playerCoords
else:
playerCoords=self.playerCoords
#Generate colors to be used
#Player waveform will turn green as it becomes more accurate
padColor,playerColor,highlight=self.generatePadColors()
if self.clicked:
#Highlight the bubble if it has been clicked on
highlightWidth=3
self.drawHighlight(gameSurface,highlight,highlightWidth)
pygame.draw.lines(gameSurface,padColor,True,
self.audioWaveFormCoords,1)
pygame.draw.lines(gameSurface,playerColor,True,playerCoords,1)
else:
#If bubble has been popped, draw it as a collapsing circle
circleWidth,dr=1,5
pygame.draw.circle(gameSurface,(255,23,68),
(int(self.x),int(self.y)),self.r,circleWidth)
self.r-=dr
if self.r<circleWidth:
self.active=False
def shiftPad(self,dx,dy):
#Shift the fourier pad by dx, dy
waveFormMaxModulation=0.2
self.x+=dx
oldY=self.y
self.y=self.cy+dy
self.audioWaveFormCoords[:,0]+=dx
self.audioWaveFormCoords[:,1]-=(oldY-self.y)
self.playerCoords[:,0]+=dx
self.playerCoords[:,1]-=(oldY-self.y)
if (self.x+self.r*(1+waveFormMaxModulation))<0:
#If the pad has been moved past the boundary of the game display,
#pop its bubble.
self.dying=True
def checkIfSlidersClicked(self):
#Check if any of the sliders associated with the fourier pad have been
#clicked.
for slider in self.sliders:
if slider.clicked:
return True
return False
class backgroundImage(pygame.sprite.Sprite):
#Class for background image (as sprite)
def __init__(self,imageFile,location,screenSize):
pygame.sprite.Sprite.__init__(self)
self.image=pygame.image.load(imageFile)
#Scale the image to the pygame screen
self.image=pygame.transform.scale(self.image,screenSize)
(self.x,self.y)=location
class fourierGame(object):
#Main game object
def gameScreenSetUp(self):
#Set up game screens
gameDisplay1WidthScaling=3/4
self.gameDisplay1Width=self.gameScreenWidth*gameDisplay1WidthScaling
self.mainBackground=pygame.Surface(self.gameScreen.get_size())
self.gameDisplay1=pygame.Surface((self.gameDisplay1Width,
self.gameScreenHeight))
playerControlWidthScaling=1/4
self.controlScreenWidth=self.gameScreenWidth*playerControlWidthScaling
ctrlScreenHeightScaling=5/6
ctrlTitleHeightScaling=1/6
self.controlScreenHeight=self.gameScreenHeight*ctrlScreenHeightScaling
self.titleScreenHeight=self.gameScreenHeight*ctrlTitleHeightScaling
self.playerControlScreen=pygame.Surface((self.controlScreenWidth,
self.controlScreenHeight))
self.playerControlTitle=pygame.Surface((self.controlScreenWidth,
self.titleScreenHeight))
self.gameOverlay=pygame.Surface((self.gameScreenWidth,
self.gameScreenHeight))
def fileManagerScreenSetUp(self):
#Set up file manager screens
fileTitleHeightScaling=1/10
fileManagerHeightScaling=9/10
self.fileManagerTitleHeight=fileTitleHeightScaling*self.gameScreenHeight
self.fileManagerHeight=fileManagerHeightScaling*self.gameScreenHeight
self.fileManagerTitle=pygame.Surface((self.gameScreenWidth,
self.fileManagerTitleHeight))
self.fileManager=pygame.Surface((self.gameScreenWidth,
self.fileManagerHeight))
def transitionScreenSetUp(self):
#Set up loading and splash screen
self.loadingScreen=pygame.Surface((self.gameScreenWidth,
self.gameScreenHeight))
self.splashScreen=pygame.Surface((self.gameScreenWidth,
self.gameScreenHeight))
def helpScreenSetUp(self):
#Sets up help screen
self.helpBackground=pygame.Surface((self.gameScreenWidth,
self.gameScreenHeight))
self.helpForeground=pygame.Surface((self.gameScreenWidth,
self.gameScreenHeight))
self.helpBackground.fill((197,17,98))
self.helpBackground=self.helpBackground.convert()
self.helpForeground.fill((255,255,255))
self.helpForegroundAlpha=200
self.helpForegroundDAlpha=-0.25
def screenSetUp(self):
#Init game screen, game display surfaces
self.computerScreenWidth=1920
self.computerScreenHeight=1080
self.gameScreen=pygame.display.set_mode((self.computerScreenWidth//2,
self.computerScreenHeight//2))
(self.gameScreenWidth,self.gameScreenHeight)=self.gameScreen.get_size()
self.gameScreenSetUp()
self.fileManagerScreenSetUp()
self.transitionScreenSetUp()
self.helpScreenSetUp()
def fontSetUp(self):
#Set up fonts
small,medium,intermediate,large=10,15,20,35
self.smallGameFont=pygame.font.SysFont("Calibri", small)
self.gameFont=pygame.font.SysFont("Calibri", medium)
self.fileManagerTitleFont=pygame.font.SysFont("Calibri",intermediate)
self.splashScreenTitleFont=pygame.font.SysFont("Calibri",large)
self.instructionFont=pygame.font.SysFont("Calibri",intermediate)
def backgroundSetUp(self):
#Set up background image
#http://orig11.deviantart.net/6a0a/f/2013/279/c/d/
#google_inspired_wallpaper_by_brebenel_silviu-d6pftbf.jpg
self.background=backgroundImage('background.jpg',
(int(self.controlScreenWidth),0),
(int(self.gameDisplay1Width),
self.gameScreenHeight))
self.backgroundLocation=(self.background.x,self.background.y)
self.background=self.background.image.convert()
def messageSetUp(self):
#setup game messages
self.gameOverMessage=self.splashScreenTitleFont.render("Game Over",
1,(0,0,0))
self.gameOverMessage=self.gameOverMessage.convert_alpha()
self.scoreMessage=""
def setGameParams(self):
#Set game parameters
self.opaque=255
self.semiTransparent=100
self.gameDisplay1Alpha=self.semiTransparent
self.playerControlScreenAlpha=self.opaque
self.playerControlTitleAlpha=self.opaque
self.gameRunning=True
def initFileManager(self):
#Initialize file manager
self.waveFiles=[]
self.txtFile='beats.txt'
self.textFileX=0
self.textFileY=0
self.textFileWidth=self.fileManager.get_width()
textFileScaling=1/9
self.textFileHeight=self.fileManager.get_height()*textFileScaling
self.waveRectHeight=0
self.noFiles=True
def setUpFileButton(self):
self.buttonWidth=40
self.buttonHeight=20
self.buttonX=self.gameDisplay1.get_width()-self.buttonWidth
self.buttonY=0
self.buttonColor=(245,0,87)
def __init__(self):
pygame.init()
self.fontSetUp()
self.screenSetUp()
self.backgroundSetUp()
self.messageSetUp()
self.gameMode="splashScreen"
self.freeze=False
self.setGameParams()
self.initFileManager()
self.splashScreenInit()
self.setUpFileButton()