使用 python 库 soundfile 读取wav音频文件为 np.array

创建日期: 2024-03-04 10:47 | 作者: 风波 | 浏览次数: 14 | 分类: Python

文档:https://python-soundfile.readthedocs.io/en/0.11.0/

The soundfile module is an audio library based on libsndfile, CFFI and NumPy.

1. 读取文件

import soundfile as sf

data, samplerate = sf.read('existing_file.wav')
sf.write('new_file.flac', data, samplerate)

分块读取

import numpy as np
import soundfile as sf

rms = [np.sqrt(np.mean(block**2)) for block in
       sf.blocks('myfile.wav', blocksize=1024, overlap=512)]

文件信息

参考:https://python-soundfile.readthedocs.io/en/0.13.1/ 腾讯混元AI

import soundfile as sf


def main():
    filename = 'xin_wen_lian_bo_2025.3.2.wav'
    with sf.SoundFile(filename) as f:
        info = {
            'channels': f.channels,      # 声道数
            'samplerate': f.samplerate,  # 采样率(Hz)
            'subtype': f.subtype,        # 子类型(如 PCM_16)
            'frames': f.frames,          # 总帧数
            'duration': f.frames / f.samplerate  # 时长(秒)
        }

    print("WAV 文件信息:")
    for key, value in info.items():
        print(f"{key}: {value}")

    wavbin, rate = sf.read(filename)
    print(wavbin)
    print(rate)


if "__main__" == __name__:
    main()

2. 读取内存

使用 io.BytesIO 封装一下二进制数据

import io
import soundfile as sf
from urllib.request import urlopen

url = "http://tinyurl.com/shepard-risset"
data, samplerate = sf.read(io.BytesIO(urlopen(url).read()))
14 浏览
13 爬虫
0 评论