8.python wave 批量截取2s音频

# @File  : sound_cut.py
# @Author: Wang Zhimin
# @Date  : 2019/10/12
import os
import wave
import numpy as np
import pylab as plt
def load_wav(path):
    """
        功能:读取文件夹下wav文件,进行2s剪切
        输入:文件夹路径
        输出:归一化后的数据
        时间:2019年10月12日
        版本:V1.0
    """

    files = []

    # 读文件

    for f in os.listdir(path):
        if not f.startswith('.') and f.endswith('.wav'):
            files.append(f)
    # 多通道处理,以及采样频率归一化
    # print(files)
    for f in files:
        w = wave.open(path+"/"+f, "rb")
        params = w.getparams()
        nchannels, sampwidth, framerate, nframes = params[:4]
        nums=int(nframes / (framerate * 2)) + 1
        # print("片段个数:",nums)
        # print("framerate",framerate)
        # print("nchannels", nchannels)
        # print("sampwidth", sampwidth)
        # print("nframes", nframes)

        str_data = w.readframes(nframes)
        wave_data = np.fromstring(str_data, dtype=np.short)
        for i in np.arange(nums):
            print((i * 2) * framerate, (i * 2 + 2) * framerate)
            # str_data1 = wave_data[0:2*framerate]
            str_data1 = wave_data[(i * 2) * framerate:(i * 2 + 2) * framerate]
            w.close()

            # 打开WAV文档
            f1 = wave.open(r"D:/work/音频剪切原始数据/"  +str(i+1)+"-"+ f, "wb")

            # 配置声道数、量化位数和取样频率
            f1.setnchannels(nchannels)
            f1.setsampwidth(sampwidth)
            f1.setframerate(framerate)
            # 将wav_data转换为二进制数据写入文件
            f1.writeframes(str_data1.tostring())
        # print(len(str_data1))
        # f1.close()
        # print(f)
    return 0


if __name__ == '__main__' :
    load_wav("D:/work/音频原始数据")

你可能感兴趣的:(wave,python)