Skip to content

Commit ed3d6fa

Browse files
committed
Improve mix by using float calculations.
1 parent a15257c commit ed3d6fa

File tree

1 file changed

+19
-6
lines changed

1 file changed

+19
-6
lines changed

synthwaveform.py

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -193,18 +193,31 @@ def mix(*waveforms: np.ndarray | tuple[np.ndarray, float]):
193193
).dtype:
194194
raise ValueError("Arrays must share the same data type")
195195

196+
# Get properties of ndarray
196197
dtype = (waveforms[0] if type(waveforms[0]) is np.ndarray else waveforms[0][0]).dtype
197198
size = np.min(
198199
[(waveform if type(waveform) is np.ndarray else waveform[0]).size for waveform in waveforms]
199200
)
200-
mid = np.sum(_minmax(dtype)) / 2
201+
minmax = _minmax(dtype)
201202

202-
data = np.empty(size, dtype=dtype) + mid
203+
# Convert to float and mix
204+
data = np.empty(size, dtype=np.float)
203205
for waveform in waveforms:
204-
data += ((waveform if type(waveform) is np.ndarray else waveform[0])[:size] - mid) * (
205-
1.0 if type(waveform) is np.ndarray else min(max(waveform[1], 0.0), 1.0)
206-
)
207-
return _prepare(data)
206+
data += (
207+
(
208+
np.array(
209+
(waveform if type(waveform) is np.ndarray else waveform[0])[:size],
210+
dtype=np.float,
211+
)
212+
- minmax[0]
213+
)
214+
/ (minmax[1] - minmax[0])
215+
* 2
216+
- 1
217+
) * (1.0 if type(waveform) is np.ndarray else waveform[1])
218+
219+
# Clip and convert to original data type
220+
return _prepare(data, dtype=dtype)
208221

209222

210223
def from_wav(path: str, max_size: int = None, channel: int = 0) -> tuple[np.ndarray, int]:

0 commit comments

Comments
 (0)