Section 181.1: 处理 WAV 文件

winsound

  • 仅适用于 Windows 环境
import winsound
winsound.PlaySound("path_to_wav_file.wav", winsound.SND_FILENAME)

wave

  • 支持单声道和立体声

  • 不支持压缩/解压缩

import wave

with wave.open("path_to_wav_file.wav", "rb") as wav_file:  # 以只读模式打开 WAV 文件
    # 获取基本信息
    n_channels = wav_file.getnchannels()  # 通道数(1=单声道,2=立体声)
    sample_width = wav_file.getsampwidth()  # 样本宽度(以字节为单位)
    framerate = wav_file.getframerate()  # 帧率
    n_frames = wav_file.getnframes()  # 帧数
    comp_type = wav_file.getcomptype()  # 压缩类型(仅支持“NONE”)
    comp_name = wav_file.getcompname()  # 压缩名称
    # 读取音频数据
    frames = wav_file.readframes(n_frames)  # 读取 n_frames 帧
    assert len(frames) == sample_width * n_frames

# 复制到一个新的 WAV 文件
with wave.open("path_to_new_wav_file.wav", "wb") as wav_file:  # 以只写模式打开 WAV 文件
    # 写入音频数据
    params = (n_channels, sample_width, framerate, n_frames, comp_type, comp_name)
    wav_file.setparams(params)
    wav_file.writeframes(frames)

Section 181.2: 使用 Python 和 FFmpeg 转换音频文件

from subprocess import check_call

ok = check_call(['ffmpeg','-i','input.mp3','output.wav'])
if ok:
  with open('output.wav', 'rb') as f:
    wav_file = f.read()

注意:

  • http://superuser.com/questions/507386/why-would-i-choose-libav-over-ffmpeg-or-is-there-even-a-difference
  • FFmpeg、libav 和 avconv 之间的相似之处和不同之处是什么?

Section 181.3: 播放 Windows 的蜂鸣声

Windows 提供了一个明确的接口,winsound 模块允许您以给定的频率和持续时间播放原始蜂鸣声。

import winsound
freq = 2500  # 设置频率为 2500 赫兹
dur = 1000  # 设置持续时间为 1000 毫秒(即 1 秒)
winsound.Beep(freq, dur)

Section 181.4: 使用 Pyglet 播放音频

import pyglet
audio = pyglet.media.load("audio.wav")
audio.play()

更多信息请参阅 Pyglet。