music.cross_fade

music.cross_fade(sonic_vector_1, sonic_vector_2, duration=500, method='lin', sample_rate=44100)[source]

Cross fade two sounds over duration milliseconds.

The tail of the first sound is faded out, the head of the second is faded in, and the two are overlapped by that duration, so the result is shorter than the two inputs laid end to end.

Parameters:
sonic_vector_1ndarray

The sound that fades out. Mono, or (2, nsamples) stereo.

sonic_vector_2ndarray

The sound that fades in, of the same number of dimensions.

durationscalar

The length of the crossfade in milliseconds.

methodstr

The fade shape, as fade() takes it: “lin” or “exp”.

sample_rateinteger

The sample rate in Hertz.

Returns:
ndarray

The two sounds overlapped, duration milliseconds shorter than their concatenation.

Raises:
ValueError

If the two sounds do not have the same number of dimensions. Crossfading a mono sound with a stereo one has no single sensible answer, so it is refused rather than guessed at.

If duration is not a positive number of samples at sample_rate, or is longer than the shorter of the two sounds. Both used to reach a NumPy broadcast failure naming two sample counts, which does not say which duration caused it.

See also

fade

the fade in or out on its own.

music.StimulationSession

crossfades that preserve total duration.

Notes

Both inputs are modified in place. The fades are applied to the caller’s arrays rather than to copies, so a sound that is crossfaded is no longer the sound it was. Pass a copy to keep the original.

The overlap makes the result shorter, which is why music.StimulationSession does not use this function: a protocol’s phase durations have to survive its transitions.

Examples

>>> joined = cross_fade(note(220, 1), note(330, 1), duration=200)
>>> len(joined) / 44100    # the overlap is 200 ms of the two seconds
1.8