wave — Read and write WAV files

Вихідний код: Lib/wave.py


The wave module provides a convenient interface to the Waveform Audio «WAVE» (or «WAV») file format.

The module supports uncompressed PCM and IEEE floating-point WAV formats.

Змінено в версії 3.12: Support for WAVE_FORMAT_EXTENSIBLE headers was added, provided that the extended format is KSDATAFORMAT_SUBTYPE_PCM.

Змінено в версії 3.15.0a7 (unreleased): Support for reading and writing WAVE_FORMAT_IEEE_FLOAT files was added.

The wave module defines the following function and exception:

wave.open(file, mode=None)

If file is a string, a path-like object or a bytes-like object open the file by that name, otherwise treat it as a file-like object. mode can be:

'rb'

Режим тільки читання.

'wb'

Режим лише запису.

Зауважте, що він не дозволяє читати/записувати файли WAV.

Режим 'rb' повертає об’єкт Wave_read, а режим 'wb' повертає об’єкт Wave_write. Якщо mode опущено, а файлоподібний об’єкт передається як file, file.mode використовується як значення за замовчуванням для mode.

If you pass in a file-like object, the wave object will not close it when its close() method is called; it is the caller’s responsibility to close the file object.

The open() function may be used in a with statement. When the with block completes, the Wave_read.close() or Wave_write.close() method is called.

Змінено в версії 3.4: Додано підтримку файлів, які неможливо шукати.

Змінено в версії 3.15: Added support for path-like objects and bytes-like objects.

exception wave.Error

Помилка виникає, коли щось неможливо, оскільки воно порушує специфікацію WAV або стикається з недоліком реалізації.

wave.WAVE_FORMAT_PCM

Format code for uncompressed PCM audio.

wave.WAVE_FORMAT_IEEE_FLOAT

Format code for IEEE floating-point audio.

wave.WAVE_FORMAT_EXTENSIBLE

Format code for WAVE extensible headers.

Об’єкти Wave_read

class wave.Wave_read

Read a WAV file.

Об’єкти Wave_read, які повертає open(), мають такі методи:

close()

Close the stream if it was opened by wave, and make the instance unusable. This is called automatically on object collection.

getnchannels()

Повертає кількість аудіоканалів (1 для моно, 2 для стерео).

getsampwidth()

Повертає ширину вибірки в байтах.

getframerate()

Повертає частоту вибірки.

getnframes()

Повертає кількість звукових кадрів.

getformat()

Returns the frame format code.

This is one of WAVE_FORMAT_PCM, WAVE_FORMAT_IEEE_FLOAT, or WAVE_FORMAT_EXTENSIBLE.

getcomptype()

Повертає тип стиснення ('NONE' є єдиним підтримуваним типом).

getcompname()

Зрозуміла для людини версія getcomptype(). Зазвичай 'not compressed' паралелі 'NONE'.

getparams()

Returns a namedtuple() (nchannels, sampwidth, framerate, nframes, comptype, compname), equivalent to output of the get*() methods.

readframes(n)

Читає та повертає щонайбільше n кадрів аудіо як об’єкт bytes.

rewind()

Перемотайте покажчик файлу на початок аудіопотоку.

Наступні два методи визначають термін «позиція», який є сумісним між ними, а в інших випадках залежить від реалізації.

setpos(pos)

Встановити вказівник файлу у вказане положення.

tell()

Повернути поточне положення покажчика файлу.

Об’єкти Wave_write

class wave.Wave_write

Write a WAV file.

Wave_write objects, as returned by open().

For seekable output streams, the wave header will automatically be updated to reflect the number of frames actually written. For unseekable streams, the nframes value must be accurate when the first frame data is written. An accurate nframes value can be achieved either by calling setnframes() or setparams() with the number of frames that will be written before close() is called and then using writeframesraw() to write the frame data, or by calling writeframes() with all of the frame data to be written. In the latter case writeframes() will calculate the number of frames in the data and set nframes accordingly before writing the frame data.

Змінено в версії 3.4: Додано підтримку файлів, які неможливо шукати.

Wave_write objects have the following methods:

close()

Make sure nframes is correct, and close the file if it was opened by wave. This method is called upon object collection. It will raise an exception if the output stream is not seekable and nframes does not match the number of frames actually written.

setnchannels(n)

Встановіть кількість каналів.

getnchannels()

Return the number of channels.

setsampwidth(n)

Встановіть ширину вибірки на n байтів.

For WAVE_FORMAT_IEEE_FLOAT, only 4-byte (32-bit) and 8-byte (64-bit) sample widths are supported.

getsampwidth()

Return the sample width in bytes.

setframerate(n)

Встановіть частоту кадрів на n.

Змінено в версії 3.2: Неінтегральний вхід у цей метод округлюється до найближчого цілого числа.

getframerate()

Return the frame rate.

setnframes(n)

Встановіть кількість кадрів на n. Це буде змінено пізніше, якщо фактично записана кількість кадрів буде іншою (ця спроба оновлення викличе помилку, якщо вихідний потік не доступний для пошуку).

getnframes()

Return the number of audio frames written so far.

setcomptype(type, name)

Встановіть тип стиснення та опис. На даний момент підтримується лише тип стиснення NONE, що означає відсутність стиснення.

getcomptype()

Return the compression type ('NONE').

getcompname()

Return the human-readable compression type name.

setformat(format)

Set the frame format code.

Supported values are WAVE_FORMAT_PCM and WAVE_FORMAT_IEEE_FLOAT.

When setting WAVE_FORMAT_IEEE_FLOAT, the sample width must be 4 or 8 bytes.

getformat()

Return the current frame format code.

setparams(tuple)

The tuple should be (nchannels, sampwidth, framerate, nframes, comptype, compname, format), with values valid for the set*() methods. Sets all parameters.

For backwards compatibility, a 6-item tuple without format is also accepted and defaults to WAVE_FORMAT_PCM.

For format=WAVE_FORMAT_IEEE_FLOAT, sampwidth must be 4 or 8.

getparams()

Return a namedtuple() (nchannels, sampwidth, framerate, nframes, comptype, compname) containing the current output parameters.

tell()

Повертає поточну позицію у файлі з тим самим застереженням для методів Wave_read.tell() і Wave_read.setpos().

writeframesraw(data)

Записуйте аудіокадри, не виправляючи nframes.

Змінено в версії 3.4: Тепер приймається будь-який bytes-like object.

writeframes(data)

Напишіть звукові кадри та переконайтеся, що nframes правильний. Це викличе помилку, якщо вихідний потік недоступний для пошуку, а загальна кількість кадрів, які були записані після запису data, не збігається з попередньо встановленим значенням для nframes.

Змінено в версії 3.4: Тепер приймається будь-який bytes-like object.

Зауважте, що не можна встановлювати будь-які параметри після виклику writeframes() або writeframesraw(), і будь-яка спроба зробити це викличе wave.Error.

For WAVE_FORMAT_IEEE_FLOAT output, a fact chunk is written as required by the WAVE specification for non-PCM formats.