-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmedia.py
More file actions
3344 lines (2994 loc) · 116 KB
/
Copy pathmedia.py
File metadata and controls
3344 lines (2994 loc) · 116 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
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
#ORIGINAL COMMENT from JES media.py BELOW
#
# Media Wrappers for "Introduction to Media Computation"
# Started: Mark Guzdial, 2 July 2002
# Revisions:
# 18 June 2003: (ellie)
# Added (blocking)play(AtRate)InRange methods to Sound class
# and global sound functions
# Changed getSampleValue, setSampleValue to give the appearance
# of 1-based indexing
# Added getLeftSampleValue and getRightSampleValue to Sound class
# 14 May 2003: Fixed discrepancy between getMediaPath and setMediaFolder (AdamW)
# 8 Nov: Fixed getSamplingRate (MarkG)
# 1 Nov: Fixed printing pixel
# 31 Oct: Fixed pickAColor (MarkG)
# 30 Oct: Added raises, fixed error messages. Added repaint (MarkG)
# 10 Oct: Coerced value to integer in Sound.setSampleValue (MarkR)
# 2 Oct: Corrected calls in setSampleValueAt (MarkG):
# 30 Aug: Made commands more consistent and add type-checking (MarkG)
# 2 Aug: Changed to getSampleValueAt and setSampleValueAt (MarkG)
# 1 Dec 2005: made max makeEmptySound size 600
# made max makeEmptyPicture dimensions 10000x10000
# fixed the off-by-one error in makeEmptyPicture
# 14 June 2007: (Pam Cutter, Kalamazoo College)
# Fixed off-by-one error in copyInto. Now allows copying
# of same-sized picture, starting at top-left corner
#
# 6 July 2007: (Pam Cutter/Alyce Brady, Kalamazoo College)
# Added flexibility to make an empty picture of a specified color. Added
# additional, 3-parameter constructor to Picture and SimplePicture classes to support this.
# Modified copyInto so that it will copy as much of the source picture as will fit
# Added crop and copyInto methods to Picture class to support these.
#
# 8 July 2007: (Pam Cutter/ Alyce Brady, Kalamazoo College)
# Changed all _class_ comparisons to use isinstance instead so that
# they will work with subclasses as well (e.g., subclasses of Picture
# are still pictures)
# Added getSampleValue, setSampleValue functions with same functionality, but
# more intuitive names, as the getSample, setSample function, respectively.
# Added global getDuration function to return the number of seconds in a sound
#
# 10 July 2007: (Pam Cutter, Kalamazoo College)
# Added a global duplicateSound function
# 11 July 2007: (Pam Cutter, Kalamazoo College)
# Added global addTextWithStyle function to allow users to add text to images
# with different font styles.
#
# 17 July 2007: (Pam Cutter, Kalamazoo College)
# Added 7global addOval, addOvalFilled, addArc and addArcFilled functions.
# Added global getNumSamples function as more meaningful name for getLength of a sound.
#
# 19 July 2007: (Pam Cutter, Kalamazoo College)
# Modified the SoundExplorer class to be consistent with sounds in JES
# starting at sample index 1.
# Modified the PictueExplorer class to initially show color values from
# pixel 1,1, instead of 0,0.
#
# 1 Nov 2007: Added __add__ and __sub__ to Color class (BrianO)
# 29 Apr 2008: Changed makeEmptySound to take an integer number of samples
# Added optional second argument to makeEmptySound for sampleRate
# 6 June 2008: Added a check for forward slash in a directory path in makeMovieFromInitialFile
# This check should work with os.altsep, but it does not work with Jython 2.2.
# This should be fixed again at a later date.
# 27 June 2008: Added optional input to setMediaFolder and setMediaPath.
# Added showMediaFolder and showMediaPath methods.
# 11 July 2007: Removed showMediaFolder and showMediaPath for no-arg version of getMediaPath/getMediaFolder.
# Added generic explore method.
# 15 July 2007: Added no-arg option for setLibPath
# TODO:
## Fix HSV/RGB conversions -- getting a divide by zero error when max=min
import sys
import os
import math
import tempfile
import numbers
import threading
import collections
import numbers
import time
#import traceback
#import user
#Don't Use PIL for images
#except one case
import PIL
#import PIL.ImageTk as ImageTk
#from os import system
#from platform import system as platform
#Use Qt for everything
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from PyQt4.QtMultimedia import * #This is for sound/video (video later)
import wave #This is for reading sound file metadata
# Create an PyQT4 application object.
#If we're running in Canopy, there already is one
root = QApplication.instance()
if root is None:
#We're not running in Canopy
#Need to launch a new application
root = QApplication(sys.argv)
#import tkinter
#from tkinter import filedialog
#from tkinter.colorchooser import askcolor
#import threading
#import org.python.core.PyString as String
#root = tkinter.Tk()
#root.withdraw()
#roots = []
# Support a media shortcut
#mediaFolder = JESConfig.getMediaPath()
#if ( mediaFolder == "" ):
mediaFolder = os.getcwd() + os.sep
# Store last pickAFile() opening
_lastFilePath = ""
true = 1
false = 0
#List of things to keep around
keepAround = []
#Check supported image types
suppTypes = QImageReader.supportedImageFormats()
supportedImageTypes = set([])
for typ in suppTypes:
supportedImageTypes.add(str(typ)[2:-1])
#Is the type of this file supported?
def isSupportedImageFormat(fname):
inddot = fname.rfind(".")
if inddot == -1:
tstr = fname
else:
tstr = fname[inddot+1:]
return tstr.lower() in supportedImageTypes
#Error reporting structure
#Lets us refactor error reporting by changing only one line of code!
def reportErrorToUser(errType, msg):
#print(msg)
raise errType(msg)
#Shortcut for ValueError reporting
def repValError(msg):
reportErrorToUser(ValueError, msg)
#Done
def setMediaPath(file=None):
global mediaFolder
if(file == None):
mediaFolder = pickAFolder()
else:
mediaFolder = file
#mediaFolder = getMediaPath()
return mediaFolder
def getMediaPath( filename = "" ):
if filename == "":
return mediaFolder
return mediaFolder + os.sep + filename
#return FileChooser.getMediaPath( filename )
#Done
def setMediaFolder(file=None):
return setMediaPath(file)
#Done
def setTestMediaFolder():
global mediaFolder
mediaFolder = os.getcwd() + os.sep
#Done
def getMediaFolder( filename = "" ):
return getMediaPath(filename)
#Done
def showMediaFolder():
global mediaFolder
print("The media path is currently: ",mediaFolder)
#Done
def getShortPath(filename):
dirs = filename.split(os.sep)
if len(dirs) < 1:
return "."
elif len(dirs) == 1:
return dirs[0]
else:
return (dirs[len(dirs) - 2] + os.sep + dirs[len(dirs) - 1])
#Done
def setLibPath(directory=None):
if(directory == None):
directory = pickAFolder()
if(os.path.isdir(directory)):
sys.path.append(directory)
else:
#print("Note: There is no directory at ",directory)
#raise ValueError
repValError("Note: There is no directory at "+str(directory))
return directory
#This is not actually a media function
#Instead, it prints lists better
def betterPrint(val):
print(recursive_str(val))
#Recursively call str on all components of val
#If val is not a sequence type, it's just str
#No need to call directly
#This is called by betterPrint
def recursive_str(val):
if isinstance(val, collections.abc.Sequence) and not isinstance(val, str):
#It's a sequence; recurse!
return str(type(val)(map(str, val)))
else:
return str(val)
#Like time.sleep, but continues to play sounds
def sleep(secs):
cur_time = time.time()
while time.time() - cur_time < secs:
QApplication.processEvents()
#Sample class
#A Sample knows its value, its position, and the Sound it's from
class Sample:
#Constructor
#Takes a Sound and a position
#Finds the value
def __init__(self, sound, pos):
self.sound = sound
self.pos = pos
self.value = sound.getSampleValue(pos)
#Convert to a printable string
def __str__(self):
return 'Sample at ' + str(self.pos) + ' with value ' + str(self.value)
#Get the Sample's value
def getValue(self):
return self.value
#Set the Sample's value
def setValue(self, newVal):
#Update the Sound
self.sound.setSampleValueRaw(self.pos, newVal)
#Update the Sample's internal value
self.value = newVal
#Get the Sound object
def getSound(self):
return self.sound
#Get the position
def getIndex(self):
return self.pos
#Sound class
#Only supports WAV for now
class Sound:
#Constants
SAMPLE_RATE = 22050
NUM_CHANNELS = 1
SAMPLE_SIZE = 16
#Default audio output device
AUDIO_DEVICE = QAudioDeviceInfo.defaultOutputDevice()
#Constructor
def __init__(self, arg1, arg2 = None):
#arg1 can be a filename, a number of samples, or a Sound
#arg2, if provided, is a sample rate
#super().__init__()
if isinstance(arg1, Sound):
#arg1 is a Sound. Copy it.
self.fileName = None #It doesn't duplicate this part
# #Instead, use a temporary file, which gets changed
# #if they save the sound
# self.tempfile = tempfile.mkstemp(suffix = '.wav')
#self.file = QFile(arg1.fileName)
self.numSamples = arg1.numSamples
self.sampleRate = arg1.sampleRate
self.sampleSize = arg1.sampleSize
self.numChannels = arg1.numChannels
#Copy the raw data
self.data = bytearray(arg1.data)
#self.writeFile(self.tempfile[1])
#self.file = QFile(self.tempfile[1])
elif isinstance(arg1, str):
#arg1 is a file name
self.fileName = arg1
#self.file = QFile(self.fileName)
#Get the metadata
wav = wave.open(self.fileName)
self.numSamples = wav.getnframes()
self.sampleRate = wav.getframerate()
self.sampleSize = wav.getsampwidth() * 8
self.numChannels = wav.getnchannels()
#Get the raw data
self.data = bytearray(wav.readframes(self.numSamples))
wav.close()
elif isinstance(arg1, int):
#arg1 is a number of samples
self.numSamples = arg1
# #Apparently the number of samples needs to be even or everything breaks?
# if self.numSamples % 2 == 1:
# self.numSamples += 1
if arg2 is None:
self.sampleRate = Sound.SAMPLE_RATE
else:
self.sampleRate = arg2
self.fileName = None
self.numChannels = Sound.NUM_CHANNELS
self.sampleSize = Sound.SAMPLE_SIZE
#Blank data
self.data = bytearray([0 for i in range(self.numSamples * self.sampleSize)])
#self.file = None
# #Use a temporary file, which gets changed
# #if they save the sound
# #TODO instead just send the sound data directly
# self.tempfile = tempfile.mkstemp(suffix = '.wav')
self.setUpFormat()
#Tuples (QBuffer, QByteArray, QAudioOutput) used for playing multiple instances
self.buffs = []
#Cleanup lock
self.cleanupLock = threading.Lock()
#self.isPlaying = False
#Set up "Samples" representation of data
#This is clunky but "necessary" for efficiency of JES operations
self.setUpSampleObjects()
# #For blocking play
# self.blockEvent = None
def setUpFormat(self):
#Create the audio format
self.format = QAudioFormat()
self.format.setCodec('audio/pcm')
self.format.setSampleRate(self.sampleRate)
self.format.setSampleSize(self.sampleSize)
self.format.setChannelCount(self.numChannels)
#This is a WAV thing
if self.sampleSize == 8:
self.format.setSampleType(QAudioFormat.UnSignedInt)
elif self.sampleSize == 16:
self.format.setSampleType(QAudioFormat.SignedInt)
self.format.setByteOrder(QAudioFormat.LittleEndian)
#print(self.sampleRate, self.sampleSize, self.numChannels)
#Convert to string
def __str__(self):
ret = "Sound"
fileName = self.fileName
#if there is a file name then add that to the output
if fileName is not None:
ret = ret + " file: " + fileName
#add the length in frames
ret = ret + " number of samples: " + str(self.getLengthInFrames())
return ret
#Number of sample
def getLengthInFrames(self):
return self.numSamples
#Get a "slice" of the raw data
def getDataSlice(self, start, stop):
return self.data[start * (self.sampleSize//8):stop * (self.sampleSize//8)]
#Play the sound
#Do nothing if it's already playing
#Play from start to stop (default is the whole sound)
def play(self, start=0, stop=0):
#if not self.isPlaying:
##Clean up zombie processes, if somehow there are some
#self.cleanUpResources()
#Make start and stop both positive
if start < 0:
newStart = self.numSamples + start
else:
newStart = start
if stop <= 0:
newStop = self.numSamples + stop
else:
newStop = stop
qba = QByteArray(self.getDataSlice(newStart, newStop))
buff = QBuffer(qba)
audioOutput = QAudioOutput(Sound.AUDIO_DEVICE, self.format)
self.buffs.append((buff, qba, audioOutput))
#print("Still alive")
#worked = self.file.open(QIODevice.ReadOnly)
#worked = self.buff.open(QIODevice.ReadOnly)
worked = self.buffs[-1][0].open(QIODevice.ReadOnly)
if not worked:
#Clean up the corrupted buffer
del self.buffs[-1]
raise IOError("Failed to open sound data stream")
#print(worked)
#Is it supported?
if not Sound.AUDIO_DEVICE.isFormatSupported(self.format):
#Clean up the corrupted buffer
del self.buffs[-1]
raise RuntimeError("Sound format not supported")
#self.audioOutput = QAudioOutput(Sound.AUDIO_DEVICE, self.format)
#worked = QObject.connect(self.audioOutput, SIGNAL('stateChanged(QAudio.State)'), self, SLOT('finishedPlaying()'))
#worked = QObject.connect(self.audioOutput, SIGNAL('stateChanged'), self, SLOT('finishedPlaying(int)'))
#worked = self.audioOutput.stateChanged.connect(self.finishedPlaying)
#self.audioOutput.stateChanged.connect(self.finishedPlaying)
self.buffs[-1][-1].stateChanged.connect(self.finishedPlaying)
#if not worked:
# raise RuntimeError("Signal binding failed")
#connect(audioOutput,SIGNAL(stateChanged(QAudio.State)),SLOT(finishedPlaying(QAudio.State)))
#self.audioOutput.start(self.file)
#self.audioOutput.start(self.buffs[-1][0])
self.buffs[-1][-1].start(self.buffs[-1][0])
QApplication.processEvents()
#self.isPlaying = True
#return audioOutput
#Plays a sound, and blocks until done
def blockingPlay(self, start=0, stop=0):
#thrd = threading.Thread(target = self.play())
#thrd.start()
#self.blockingEvent = threading.Event()
self.play(start, stop)
# cv = threading.Condition()
# cv.acquire()
# while len(self.buffs) > 0:
# cv.wait(0.01)
# #cv.wait_for(lambda: len(self.buffs) == 0)
# cv.release()
while len(self.buffs) > 0:
#Hang around here
QApplication.processEvents() #YES!!!!!
#self.blockingEvent.wait()
#self.blockingEvent = None
#thrd.join()
#time.sleep(2)
#Is the sound currently playing?
def isPlaying(self):
return len(self.buffs) > 0
#Stop the sound from playing (however many times it's currently playing)
def stopPlaying(self):
#Acquire the cleanup lock
self.cleanupLock.acquire()
try:
#Clean up ALL instances of playing the sound
buffs = list(self.buffs)
for i in range(len(buffs)-1, -1, -1):
self.buffs[i][-1].stop()
self.buffs[i][0].close()
del self.buffs[i]
finally:
#Release the lock
self.cleanupLock.release()
#Go through the list of playing sound resources and destroy
#the ones that have finished playing
def cleanUpResources(self):
#Acquire lock; don't want multiple threads in here at once
self.cleanupLock.acquire()
try:
#Clean up finished instances of playing the sound
buffs = list(self.buffs)
for i in range(len(buffs)-1, -1, -1):
if buffs[i][0].atEnd():
#This one's done
self.buffs[i][0].close()
self.buffs[i][-1].stop()
del self.buffs[i]
# if len(self.buffs) == 0 and self.blockingEvent is not None:
# #Wake up the block!
# self.blockingEvent.set()
finally:
QApplication.processEvents()
#Release the lock
self.cleanupLock.release()
#It was working with files, but failed with buffers (triggered too soon)
#Workaround is to manually call the clean up method
def finishedPlaying(self, state):
#print("yo", state)
#state = self.audioOutput.state()
#Is it finished?
if state == QAudio.IdleState:
# self.audioOutput.stop()
# #self.file.close()
# self.buff.close()
# self.isPlaying = False
# print("It's done!")
self.cleanUpResources()
#Write this sound to the given
def writeToFile(self, fil):
fd = wave.open(fil, 'wb')
fd.setnchannels(self.numChannels)
fd.setnframes(self.numSamples)
fd.setframerate(self.sampleRate)
fd.setsampwidth(self.sampleSize // 8)
fd.writeframes(self.data)
fd.close()
#Represent the sound as an image of the given dimensions
#Used by Sound Explorer
def getImageRep(self, width, height):
#Find the height in the image of a given sample value
def findY(sval):
if self.sampleSize == 8:
return int((-height/256)*sval + height-1)
elif self.sampleSize == 16:
return int((-height/65536)*sval + height/2)
#Create an empty black picture
ret = makeEmptyPicture(width, height, black)
#Add the waveform, adjusted for proper step size
lastY = findY(getSampleValueAt(self, 0))
stepSize = max(self.numSamples // width, 1)
for i in range(stepSize, self.numSamples, stepSize):
curY = findY(getSampleValueAt(self, i))
addLine(ret, i//stepSize-1, lastY, i//stepSize, curY, white)
lastY = curY
#Add the zero line
if self.sampleSize == 8:
addLine(ret, 0, height-1, width-1, height-1, cyan)
elif self.sampleSize == 16:
addLine(ret, 0, height//2, width-1, height//2, cyan)
return ret
def setUpSampleObjects(self):
ss = self.sampleSize // 8
if len(self.data) % ss != 0:
#The samples are corrupted
raise ValueError("You have half a sample at the end. Not sure why.")
self.samples = []
#Convert the binary stream to integers by sample size
#Make sure to use two's complement
for i in range(self.numSamples):
self.samples.append(Sample(self, i))
#Get the ith sample value
def getSampleValue(self, i):
if self.sampleSize == 8:
#This is easy
val = int(self.data[i])
elif self.sampleSize == 16:
#This is harder
val = int.from_bytes(self.data[2*i:2*i+2], 'little', signed=True)
# val = self.data[2*i] * 256 + self.data[2*i+1]
# if val >= 32768:
# #Need to make it be negative
# val -= 65536
return val
def getSample(self, i):
return self.samples[i]
#Get all the samples, as a list
#DO NOT PRINT THIS!!!
def getSamples(self):
# ss = self.sampleSize // 8
# if len(self.data) % ss != 0:
# #The samples are corrupted
# raise ValueError("You have half a sample at the end. Not sure why.")
# ret = []
# #Convert the binary stream to integers by sample size
# #Make sure to use two's complement
# for i in range(self.numSamples):
# ret.append(self.getSample(i))
# return ret
return self.samples
#Set a sample value
#DOES change the Sample objects
def setSampleValue(self, pos, value):
#Clipping
val = value
if val < -32768:
val = -32768
elif val > 32767:
val = 32767
self.samples[pos].setValue(val)
#Set the value of the sample at position pos to value
#DO NOT CALL THIS IF YOU ARE USING Sample OBJECTS!
#This is called by Sample to update the Sound
#It will desync the Sample objects if you call it directly
def setSampleValueRaw(self, pos, value):
if self.sampleSize == 8:
#This is easy
self.data[pos] = value
elif self.sampleSize == 16:
#This is harder
# #First, un-two's-complement it
# val = value
# if val < 0:
# val = val + 65536
# #Then, extract the bytes
# hiByte = val // 256
# loByte = val % 256
# #Finally, set the data
# self.data[2*pos] = hiByte
# self.data[2*pos+1] = loByte
val = value.to_bytes(2, 'little', signed=True)
self.data[2*pos:2*pos+2] = val
#What is the sample size, in bits?
def getSampleSize(self):
return self.sampleSize
#What is the sampling rate?
def getSamplingRate(self):
return self.sampleRate
##
## Global sound functions
##
#Done
def makeSound(filename):
global mediaFolder
if not os.path.isabs(filename):
filename = mediaFolder + filename
if not os.path.isfile(filename):
#print("There is no file at "+filename)
#raise ValueError
repValError("There is no file at "+filename)
return Sound(filename)
# MMO (1 Dec 2005): capped size of sound to 600
# Brian O (29 Apr 2008): changed first argument to be number of samples, added optional 2nd argument of sampling rate
#Done
def makeEmptySound(numSamples, samplingRate = Sound.SAMPLE_RATE):
if numSamples <= 0 or samplingRate <= 0:
#print("makeEmptySound(numSamples[, samplingRate]): numSamples and samplingRate must each be greater than 0")
#raise ValueError
repValError("makeEmptySound(numSamples[, samplingRate]): numSamples and samplingRate must each be greater than 0")
if (numSamples/samplingRate) > 600:
#print("makeEmptySound(numSamples[, samplingRate]): Created sound must be less than 600 seconds")
#raise ValueError
repValError("makeEmptySound(numSamples[, samplingRate]): Created sound must be less than 600 seconds")
if not isinstance(numSamples, int):
repValError("makeEmptySound(numSamples[, samplingRate]): numSamples must be an integer")
if not isinstance(samplingRate, int):
repValError("makeEmptySound(numSamples[, samplingRate]): samplingRate must be an integer")
return Sound(numSamples, samplingRate)
# if size > 600:
# #print "makeEmptySound(size): size must be 600 seconds or less"
# #raise ValueError
# repValError("makeEmptySound(size): size must be 600 seconds or less")
# return Sound(size * Sound.SAMPLE_RATE)
# Brian O (5 May 2008): Added method for creating sound by duration
#Done
def makeEmptySoundBySeconds(seconds, samplingRate = Sound.SAMPLE_RATE):
if seconds <= 0 or samplingRate <= 0:
#print("makeEmptySoundBySeconds(numSamples[, samplingRate]): numSamples and samplingRate must each be greater than 0")
#raise ValueError
repValError("makeEmptySoundBySeconds(numSamples[, samplingRate]): numSamples and samplingRate must each be greater than 0")
if seconds > 600:
#print("makeEmptySoundBySeconds(numSamples[, samplingRate]): Created sound must be less than 600 seconds")
#raise ValueError
repValError("makeEmptySoundBySeconds(numSamples[, samplingRate]): Created sound must be less than 600 seconds")
return Sound(int(seconds * samplingRate), samplingRate)
# PamC: Added this function to duplicate a sound
#Done
def duplicateSound(sound):
if not isinstance(sound, Sound):
#print("duplicateSound(sound): Input is not a sound")
#raise ValueError
repValError("duplicateSound(sound): Input is not a sound")
return Sound(sound)
#Done
def getSamples(sound):
if not isinstance(sound, Sound):
#print("getSamples(sound): Input is not a sound")
#raise ValueError
repValError("getSamples(sound): Input is not a sound")
return sound.getSamples()
#Done
def play(sound):
if not isinstance(sound,Sound):
#print "play(sound): Input is not a sound"
#raise ValueError
repValError("play(sound): Input is not a sound")
sound.play()
#DONE!!!!!!!!!
#(Note: "blocking main thread" includes infinite loop)
def blockingPlay(sound):
if not isinstance(sound,Sound):
#print "blockingPlay(sound): Input is not a sound"
#raise ValueError
repValError("blockingPlay(sound): Input is not a sound")
sound.blockingPlay()
# Buck Scharfnorth (27 May 2008): Added method for stopping play of a sound
#Done
def stopPlaying(sound):
if not isinstance(sound,Sound):
#print "stopPlaying(sound): Input is not a sound"
#raise ValueError
repValError("stopPlaying(sound): Input is not a sound")
sound.stopPlaying()
# def playAtRate(sound,rate):
# #if not isinstance(sound, Sound):
# # #print "playAtRate(sound,rate): First input is not a sound"
# # #raise ValueError
# # repValError("playAtRate(sound,rate): First input is not a sound")
# ## sound.playAtRate(rate)
# #sound.playAtRateDur(rate,sound.getLength())
# pass #TODO
#
# def playAtRateDur(sound,rate,dur):
# #if not isinstance(sound,Sound):
# # #print "playAtRateDur(sound,rate,dur): First input is not a sound"
# # #raise ValueError
# # repValError("playAtRateDur(sound,rate,dur): First input is not a sound")
# #sound.playAtRateDur(rate,dur)
# pass #TODO
#20June03 new functionality in JavaSound (ellie)
def playInRange(sound,start,stop):
if not isinstance(sound, Sound):
repValError("playInRange(sound,start,stop): First input is not a sound")
elif not isinstance(start, int):
repValError("playInRange(sound,start,stop): Second input is not an integer")
elif start < 0:
repValError("playInRange(sound,start,stop): Second input cannot be negative")
elif start >= getNumSamples(sound):
repValError("playInRange(sound,start,stop): Second input cannot be greater than the length of the sound, which is " + getNumSamples(sound))
elif not isinstance(stop, int):
repValError("playInRange(sound,start,stop): Third input is not an integer")
elif stop < 0:
repValError("playInRange(sound,start,stop): Third input cannot be negative")
elif stop >= getNumSamples(sound):
repValError("playInRange(sound,start,stop): Third input cannot be greater than the length of the sound, which is " + getNumSamples(sound))
elif start > stop:
repValError("playInRange(sound,start,stop): Second input cannot exceed third input")
# sound.playInRange(start,stop)
#sound.playAtRateInRange(1,start-Sound._SoundIndexOffset,stop-Sound._SoundIndexOffset)
sound.play(start, stop)
# #20June03 new functionality in JavaSound (ellie)
#Done
def blockingPlayInRange(sound,start,stop):
if not isinstance(sound, Sound):
repValError("playInRange(sound,start,stop): First input is not a sound")
elif not isinstance(start, int):
repValError("playInRange(sound,start,stop): Second input is not an integer")
elif start < 0:
repValError("playInRange(sound,start,stop): Second input cannot be negative")
elif start >= getNumSamples(sound):
repValError("playInRange(sound,start,stop): Second input cannot be greater than the length of the sound, which is " + getNumSamples(sound))
elif not isinstance(stop, int):
repValError("playInRange(sound,start,stop): Third input is not an integer")
elif stop < 0:
repValError("playInRange(sound,start,stop): Third input cannot be negative")
elif stop >= getNumSamples(sound):
repValError("playInRange(sound,start,stop): Third input cannot be greater than the length of the sound, which is " + getNumSamples(sound))
elif start > stop:
repValError("playInRange(sound,start,stop): Second input cannot exceed third input")
sound.blockingPlay(start, stop)
#
# #20June03 new functionality in JavaSound (ellie)
# def playAtRateInRange(sound,rate,start,stop):
# #if not isinstance(sound,Sound):
# # #print "playAtRateInRAnge(sound,rate,start,stop): First input is not a sound"
# # #raise ValueError
# # repValError("playAtRateInRAnge(sound,rate,start,stop): First input is not a sound")
# #sound.playAtRateInRange(rate,start - Sound._SoundIndexOffset,stop - Sound._SoundIndexOffset)
# pass #TODO
#
# #20June03 new functionality in JavaSound (ellie)
# def blockingPlayAtRateInRange(sound,rate,start,stop):
# #if not isinstance(sound, Sound):
# # #print "blockingPlayAtRateInRange(sound,rate,start,stop): First input is not a sound"
# # #raise ValueError
# # repValError("blockingPlayAtRateInRange(sound,rate,start,stop): First input is not a sound")
# #sound.blockingPlayAtRateInRange(rate, start - Sound._SoundIndexOffset,stop - Sound._SoundIndexOffset)
# pass #TODO
#New
#Is the sound currently playing?
def isPlaying(sound):
if not isinstance(sound, Sound):
#print "getSamplingRate(sound): Input is not a sound"
#raise ValueError
repValError("isPlaying(sound): Input is not a sound")
return sound.isPlaying()
#Done
def getSamplingRate(sound):
if not isinstance(sound, Sound):
#print "getSamplingRate(sound): Input is not a sound"
#raise ValueError
repValError("getSamplingRate(sound): Input is not a sound")
return sound.getSamplingRate()
#Done
def setSampleValueAt(sound,index,value):
if not isinstance(sound, Sound):
repValError("setSampleValueAt(sound,index,value): First input is not a sound")
if index < 0:
repValError("You asked for the sample at index: " + str( index ) + ". This number is less than " + str(0) + ". Please try" + " again using an index in the range [" + str(0) + "," + str ( getLength( sound ) - 1 ) + "].")
if index > getLength(sound) - 1:
repValError("You are trying to access the sample at index: " + str( index ) + ", but the last valid index is at " + str( getLength( sound ) - 1 ))
sound.setSampleValue(index, int(value))
#Done
def getSampleValueAt(sound,index):
if not isinstance(sound,Sound):
repValError("getSampleValueAt(sound,index): First input is not a sound")
if index < 0:
repValError("You asked for the sample at index: " + str( index ) + ". This number is less than 0. Please try" + " again using an index in the range [" + str(0) + "," + str ( getLength( sound ) - 1) + "].")
if index > getLength(sound) - 1:
repValError("You are trying to access the sample at index: " + str( index ) + ", but the last valid index is at " + str( getLength( sound ) - 1 ))
return sound.getSampleValue(index)
#Done
def getSampleObjectAt(sound,index):
if not isinstance(sound, Sound):
repValError("getSampleObjectAt(sound,index): First input is not a sound")
if index < 0:
repValError("You asked for the sample at index: " + str( index ) + ". This number is less than " + str(0) + ". Please try" + " again using an index in the range [" + str(0) + "," + str ( getLength( sound ) - 1 ) + "].")
if index > getLength(sound) - 1:
repValError("You are trying to access the sample at index: " + str( index ) + ", but the last valid index is at " + str( getLength( sound ) - 1 ))
return sound.getSample(index)
#New
#Get sample size, in bits
#Usually would be 16, but this code supports 8 as well
def getSampleSize(sound):
if not isinstance(sound, Sound):
repValError("getSampleSize(sound): Input is not a sound")
return sound.getSampleSize()
#Done
def setSample(sample, value):
if not isinstance(sample,Sample):
repValError("setSample(sample,value): First input is not a Sample")
ss = getSampleSize(getSound(sample))
if ss == 8:
vmax = 255
vmin = 0
elif ss == 16:
vmax = 32767
vmin = -32768
#Clip
if value > vmax:
value = vmax
elif value < vmin:
value = vmin
# Need to coerce value to integer
sample.setValue( int(value) )
# PamC: Added this function to be a better name than setSample
#Done
def setSampleValue(sample, value):
setSample(sample, value)
#Done
def getSample(sample):
if not isinstance(sample, Sample):
repValError("getSample(sample): Input is not a Sample")
return sample.getValue()
# PamC: Added this to be a better name for getSample
#Done
def getSampleValue(sample):
return getSample(sample)
#New
def getSampleIndex(sample):
if not isinstance(sample, Sample):
repValError("getSampleIndex(sample): Input is not a Sample")
return sample.getIndex()
#Done
def getSound(sample):
if not isinstance(sample,Sample):
repValError("getSound(sample): Input is not a Sample")
return sample.getSound()
#Done
def getLength(sound):
if not isinstance(sound, Sound):
repValError("getLength(sound): Input is not a Sound")
return sound.getLengthInFrames()
# PamC: Added this function as a more meaningful name for getLength
#Done
def getNumSamples(sound):
return getLength(sound)
# PamC: Added this function to return the number of seconds
# in a sound
#Done
def getDuration(sound):
if not isinstance(sound, Sound):
repValError("getDuration(sound): Input is not a Sound")
return getLength(sound) / getSamplingRate(sound)
#New
#Frequency: Hertz
#Amplitude: Max/min of the sine wave (should be between 0 and 32767)
#Dur: Length, in seconds
def pureTone(freq, amp, dur):
if not isinstance(freq, numbers.Number):
repValError("pureTone(freq, amp, dur): freq must be a number")
elif freq < 0:
repValError("pureTone(freq, amp, dur): freq must be nonnegative")
if not isinstance(amp, numbers.Number):
repValError("pureTone(freq, amp, dur): amp must be a number")
elif amp < 0 or amp > 32767:
repValError("pureTone(freq, amp, dur): amp must be between 0 and 32767 (inclusive)")
if not isinstance(dur, numbers.Number):
repValError("pureTone(freq, amp, dur): dur must be a number")
elif dur < 0:
repValError("pureTone(freq, amp, dur): dur must be nonnegative")
def getVal(i):
return int(amp*math.sin((freq*2*math.pi)*i/Sound.SAMPLE_RATE))
sound = makeEmptySoundBySeconds(dur)
for i in range(int(dur * Sound.SAMPLE_RATE)):
setSample(getSampleObjectAt(sound, i), getVal(i))
return sound
#Done
def writeSoundTo(sound,filename):
global mediaFolder
if not os.path.isabs(filename):
filename = mediaFolder + filename
if not isinstance(sound, Sound):
repValError("writeSoundTo(sound,filename): First input is not a Sound")
sound.writeToFile(filename)
#New
def saveSound(sound):
fil = pickASaveFile()
#Try to get a format
#If no format given, yell at the user
# dotloc = fil.rfind(".")
# if dotloc == -1:
# repValError("Error: No file extension provided")
# #raise ValueError("Error: No file extension provided")
if len(fil) < 4 or (fil[-4:] != '.wav' and fil[-4:] != '.WAV'):
repValError("Error: Must specify .wav extension")
writeSoundTo(sound, fil)
##
# Globals for styled text
##
#Done
def makeStyle(fontName,emph,size):
ret = QFont()
#ret.setStyleName(fontName)
ret.setPointSize(size)
#if emph == sansSerif or emph == serif or emph == mono:
# ret.setStyleHint(emph)
ret.setStyleHint(fontName)
if emph == italic:
ret.setStyle(emph)
elif emph == bold or emph == plain:
ret.setWeight(emph)
return ret
sansSerif = QFont.SansSerif
serif = QFont.Serif
mono = QFont.Monospace
italic = QFont.StyleItalic
bold = QFont.Bold
plain = QFont.Normal