Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Đọc và ghi file AIFF/AIFC với module aifc trong Python

Module aifc hỗ trợ đọc/ghi file AIFF (Audio Interchange File Format) và AIFF-C (có nén).

Tham số audio quan trọng

  • Frame rate: Số mẫu/giây (sampling rate)
  • Channels: Mono (1), Stereo (2), Quadro (4)
  • Frame: 1 mẫu trên mỗi kênh
  • Sample size: Kích thước mẫu (bytes)

Dung lượng 1 giây = channels × samplesize × framerate (bytes)

Ghi file (write mode)

aiff()Tạo file AIFF
aifc()Tạo file AIFF-C
setnchannels(n)Số kênh
setsampwidth(n)Độ rộng mẫu (bytes)
setframerate(n)Tần số lấy mẫu
setnframes(n)Số frame
setcomptype(type, name)Loại nén: NONE, ULAW, ALAW, G722
setparams(tuple)Thiết lập tất cả
writeframes(data)Ghi dữ liệu (cập nhật header)
writeframesraw(data)Ghi dữ liệu (không cập nhật header)

Ví dụ tạo file AIFF

import aifc, struct, random

sampleRate = 44100.0
obj = aifc.open('sound.aiff', 'w')
obj.setnchannels(1)
obj.setsampwidth(2)
obj.setframerate(int(sampleRate))

for i in range(99999):
    value = random.randint(-32767, 32767)
    data = struct.pack('

Đọc file (read mode)

getnchannels()Số kênh
getsampwidth()Độ rộng mẫu
getframerate()Tần số lấy mẫu
getnframes()Số frame
getcomptype()Loại nén (bytes)
getparams()Namedtuple tất cả tham số
readframes(n)Đọc n frame
setpos(pos)Seek đến frame

Phương thức chung (read/write)

rewind()Quay về đầu file
tell()Vị trí frame hiện tại
close()Đóng file

Ví dụ đọc thông tin file

import aifc

obj = aifc.open('sound.aiff', 'r')
print("Số kênh:", obj.getnchannels())
print("Độ rộng mẫu:", obj.getsampwidth())
print("Tần số:", obj.getframerate())
print("Số frame:", obj.getnframes())
print("Tham số:", obj.getparams())
obj.close()

Kết quả

Số kênh: 1
Độ rộng mẫu: 2
Tần số: 44100
Số frame: 99999
Tham số: _aifc_params(nchannels=1, sampwidth=2, framerate=44100, nframes=99999, comptype=b'NONE', compname=b'not compressed')