21.5. wave —读写 WAV 文件

源代码: Lib/wave.py


wave模块为 WAV 声音格式提供了方便的界面。它不支持压缩/解压缩,但支持单声道/立体声。

wave模块定义以下Function和异常:

  • wave. open(* file * [,* mode *])

    • 如果* file *是字符串,请使用该名称打开文件,否则将其视为可搜索的类似于文件的对象。 模式可以是以下任何一种
  • 'r' , 'rb'

    • 只读模式。

    • 'w' , 'wb'

      • 只写模式。

请注意,它不允许读/写 WAV 文件。

'r''rb'的* mode 返回Wave_read对象,而'w''wb' mode 返回Wave_write对象。如果Ellipsis mode 且将类似文件的对象作为 file 传递,则file.mode用作 mode *的默认值(如有必要,仍添加'b'标志)。

如果传入类似文件的对象,则在调用其close()方法时,wave 对象不会将其关闭;关闭文件对象是调用者的责任。

  • wave. openfp(* file mode *)

    • open()的同义词,为向后兼容而保留。
  • exception wave. Error

    • 当某些事情由于违反 WAV 规范或遇到实现缺陷而无法执行时,将引发错误。

21.5.1. Wave_read 对象

open()返回的 Wave_read 对象具有以下方法:

  • Wave_read. close ( )

    • 如果流是由wave打开的,请关闭该流,并使该实例不可用。这在对象收集时自动调用。
  • Wave_read. getnchannels ( )

    • 返回音频通道数(单声道为1,立体声为2)。
  • Wave_read. getsampwidth ( )

    • 返回以字节为单位的 samples 宽度。
  • Wave_read. getframerate ( )

    • 返回采样频率。
  • Wave_read. getnframes ( )

    • 返回音频帧数。
  • Wave_read. getcomptype ( )

    • 返回压缩类型('NONE'是唯一受支持的类型)。
  • Wave_read. getcompname ( )

    • getcomptype()的可读版本。通常'not compressed'Parallel'NONE'
  • Wave_read. getparams ( )

    • 返回一个 Tuples(nchannels, sampwidth, framerate, nframes, comptype, compname),等效于get*()方法的输出。
  • Wave_read. readframes(* n *)

    • 读取并返回最多* n *帧音频,作为一个字节字符串。
  • Wave_read. rewind ( )

    • 将文件指针倒退到音频流的开头。

为了与aifc模块兼容,定义了以下两种方法,并且没有做任何有趣的事情。

  • Wave_read. getmarkers ( )

    • 返回None
  • Wave_read. getmark(* id *)

    • 引发错误。

以下两种方法定义了术语“位置”,它们在它们之间是兼容的,否则与实现有关。

  • Wave_read. setpos(* pos *)

    • 将文件指针设置到指定位置。
  • Wave_read. tell ( )

    • 返回当前文件指针位置。

21.5.2. Wave_write 对象

open()返回的 Wave_write 对象具有以下方法:

  • Wave_write. close ( )

    • 确保* nframes *是正确的,如果文件是由wave打开的,则将其关闭。在对象收集时调用此方法。
  • Wave_write. setnchannels(* n *)

    • 设置 Channels 数。
  • Wave_write. setsampwidth(* n *)

    • 将 samples 宽度设置为* n *个字节。
  • Wave_write. setframerate(* n *)

    • 将帧频设置为* n *。
  • Wave_write. setnframes(* n *)

    • 将帧数设置为* n *。如果写入更多帧,以后将更改。
  • Wave_write. setcomptype(* type name *)

    • 设置压缩类型和描述。目前,仅支持压缩类型NONE,表示不压缩。
  • Wave_write. setparams(* tuple *)

      • tuple *应该是(nchannels, sampwidth, framerate, nframes, comptype, compname),其值对于set*()方法有效。设置所有参数。
  • Wave_write. tell ( )

  • Wave_write. writeframesraw(* data *)

    • 编写音频帧,而不校正* nframes *。
  • Wave_write. writeframes(* data *)

    • 编写音频帧,并确保* nframes *正确。

请注意,在调用writeframes()writeframesraw()之后设置任何参数都是无效的,任何try都会引发wave.Error