Show More
@@ -104,24 +104,47 b' class Audio(DisplayObject):' | |||||
104 | import struct |
|
104 | import struct | |
105 | from io import BytesIO |
|
105 | from io import BytesIO | |
106 | import wave |
|
106 | import wave | |
|
107 | ||||
107 | try: |
|
108 | try: | |
108 | import numpy as np |
|
109 | import numpy as np | |
|
110 | ||||
109 | data = np.array(data,dtype=float) |
|
111 | data = np.array(data, dtype=float) | |
110 |
if len(data.shape) |
|
112 | if len(data.shape) == 1: | |
111 | raise ValueError("encoding of stereo PCM signals are unsupported") |
|
113 | nchan = 1 | |
|
114 | elif len(data.shape) == 2: | |||
|
115 | # In wave files,channels are interleaved. E.g., | |||
|
116 | # "L1R1L2R2..." for stereo. See | |||
|
117 | # http://msdn.microsoft.com/en-us/library/windows/hardware/dn653308(v=vs.85).aspx | |||
|
118 | # for channel ordering | |||
|
119 | nchan = data.shape[0] | |||
|
120 | data = data.T.ravel() | |||
|
121 | else: | |||
|
122 | raise ValueError('Array audio input must be a 1D or 2D array') | |||
112 | scaled = np.int16(data/np.max(np.abs(data))*32767).tolist() |
|
123 | scaled = np.int16(data/np.max(np.abs(data))*32767).tolist() | |
113 | except ImportError: |
|
124 | except ImportError: | |
|
125 | # check that it is a "1D" list | |||
|
126 | idata = iter(data) # fails if not an iterable | |||
|
127 | try: | |||
|
128 | iter(idata.next()) | |||
|
129 | raise TypeError('Only lists of mono audio are ' | |||
|
130 | 'supported if numpy is not installed') | |||
|
131 | except TypeError: | |||
|
132 | # this means it's not a nested list, which is what we want | |||
|
133 | pass | |||
114 | maxabsvalue = float(max([abs(x) for x in data])) |
|
134 | maxabsvalue = float(max([abs(x) for x in data])) | |
115 |
scaled = [int(x/maxabsvalue*32767) for x in data] |
|
135 | scaled = [int(x/maxabsvalue*32767) for x in data] | |
|
136 | nchan = 1 | |||
|
137 | ||||
116 | fp = BytesIO() |
|
138 | fp = BytesIO() | |
117 | waveobj = wave.open(fp,mode='wb') |
|
139 | waveobj = wave.open(fp,mode='wb') | |
118 |
waveobj.setnchannels( |
|
140 | waveobj.setnchannels(nchan) | |
119 | waveobj.setframerate(rate) |
|
141 | waveobj.setframerate(rate) | |
120 | waveobj.setsampwidth(2) |
|
142 | waveobj.setsampwidth(2) | |
121 | waveobj.setcomptype('NONE','NONE') |
|
143 | waveobj.setcomptype('NONE','NONE') | |
122 | waveobj.writeframes(b''.join([struct.pack('<h',x) for x in scaled])) |
|
144 | waveobj.writeframes(b''.join([struct.pack('<h',x) for x in scaled])) | |
123 | val = fp.getvalue() |
|
145 | val = fp.getvalue() | |
124 | waveobj.close() |
|
146 | waveobj.close() | |
|
147 | ||||
125 |
return val |
|
148 | return val | |
126 |
|
149 | |||
127 | def _data_and_metadata(self): |
|
150 | def _data_and_metadata(self): |
General Comments 0
You need to be logged in to leave comments.
Login now