music.write_audio

music.write_audio(sonic_vector=None, filename='asound.wav', sample_rate=None, fades_ms=0, bit_depth=16, remove_bias=True, normalize=True, **renamed)[source]

Write a sound to a file, mono or stereo, WAV or FLAC.

The container comes from the extension and the channel count from the array, so a caller who has a sound and a path does not have to dispatch on either.

Parameters:
sonic_vectorarray_like, optional

The PCM samples to write: (nsamples,) for mono or (2, nsamples) for stereo. Defaults to about two seconds of uniform noise, as the two writers below do.

filenamestr

The path to write. .wav and .flac are understood.

sample_ratescalar or None

The sample frequency. None, the default, is the rate music.get_sample_rate() returns.

fades_msiterable or scalar

Milliseconds of fade in and fade out, either as a pair or as a single value applied to both ends.

bit_depthinteger

Bits per sample: 8, 16, 24 or 32 for WAV, and 8, 16 or 24 for FLAC, which has no 32-bit form.

remove_biasbool

Whether to remove the bias, or offset. Part of normalizing, so it has no effect when normalize is False.

normalizebool

Normalize to full scale, as by default, or write the samples as they are, refusing a sound that reaches past [-1, 1].

**renamed

fades, the name fades_ms had before it said its unit. Still accepted, with a DeprecationWarning.

Returns:
None

The sound is written to filename.

Raises:
ValueError

If the extension is not one this package writes, the bit depth is not one the chosen container can hold, the sound is empty, or, with normalize=False, it reaches past [-1, 1]; or if fades_ms is neither one value nor two, or is negative.

Parameters:
  • sonic_vector (ArrayLike | None)

  • filename (str)

  • sample_rate (int | None)

  • fades_ms (Sequence[int] | int)

  • bit_depth (int)

  • remove_bias (bool)

  • normalize (bool)

  • renamed (Any)

Return type:

None

See also

write_wav_mono

the mono writer, with the same arguments.

write_wav_stereo

the stereo writer, which can also normalize the channels separately.

read_audio

reads back what these write.

Notes

FLAC is lossless, so it is a smaller file and not a different sound: a rendered stimulus read back from FLAC is sample for sample the one that was written, which the round-trip tests check at every depth. That matters here more than it does in most libraries, because the claim this package makes is about the samples.

Lossy containers are deliberately not offered. Discarding what a listener is unlikely to notice is the one thing a package whose subject is fidelity to a mathematical model should not do quietly.

Examples

>>> write_audio(note(duration=1), "note.flac")
>>> write_audio(localize_linear(note()), "moving.wav")