Show More
@@ -104,24 +104,47 b' class Audio(DisplayObject):' | |||
|
104 | 104 | import struct |
|
105 | 105 | from io import BytesIO |
|
106 | 106 | import wave |
|
107 | ||
|
107 | 108 | try: |
|
108 | 109 | import numpy as np |
|
110 | ||
|
109 | 111 | data = np.array(data,dtype=float) |
|
110 |
if len(data.shape) |
|
|
111 | raise ValueError("encoding of stereo PCM signals are unsupported") | |
|
112 | if len(data.shape) == 1: | |
|
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 | 123 | scaled = np.int16(data/np.max(np.abs(data))*32767).tolist() |
|
113 | 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 | 134 | maxabsvalue = float(max([abs(x) for x in data])) |
|
115 | 135 |
scaled = [int(x/maxabsvalue*32767) for x in data] |
|
136 | nchan = 1 | |
|
137 | ||
|
116 | 138 | fp = BytesIO() |
|
117 | 139 | waveobj = wave.open(fp,mode='wb') |
|
118 |
waveobj.setnchannels( |
|
|
140 | waveobj.setnchannels(nchan) | |
|
119 | 141 | waveobj.setframerate(rate) |
|
120 | 142 | waveobj.setsampwidth(2) |
|
121 | 143 | waveobj.setcomptype('NONE','NONE') |
|
122 | 144 | waveobj.writeframes(b''.join([struct.pack('<h',x) for x in scaled])) |
|
123 | 145 | val = fp.getvalue() |
|
124 | 146 | waveobj.close() |
|
147 | ||
|
125 | 148 |
return val |
|
126 | 149 | |
|
127 | 150 | def _data_and_metadata(self): |
General Comments 0
You need to be logged in to leave comments.
Login now