【python】保存wav文件

参考大佬博客:python音频处理用到的操作

import wave, os, struct, librosa
import numpy as np
'''mono-channel audio file'''

# wav文件读取
filepath = "./wavs/"  
filename= os.listdir(filepath)                                        # 所有文件名称 
wfile = filepath + filename[1]
print(wfile)
f = wave.open(wfile, 'rb')
params = f.getparams()
print(params)
nchannels, sampwidth, framerate, nframes = params[:4]
strData = f.readframes(nframes)                                  # 读取音频,字符串格式
waveData_ = np.frombuffer(strData, dtype = np.int16)         # 将字符串转化为int, CHANGE
waveData = waveData_ * 1.0 / (max(abs(waveData_)))        # 幅值归一化, librosa-like data
f.close()

# wav文件写入
outData = waveData                                                   # 待写入wav的数据
outfile = filepath + 'out1.wav'
outwave = wave.open(outfile, 'wb')                               # 定义存储路径以及文件名
nchannels = 1
sampwidth = 2
fs = 16000
data_size = len(outData)
framerate = int(fs)
nframes = data_size
comptype = "NONE"
compname = "not compressed"
outwave.setparams((nchannels, sampwidth, framerate, nframes,
    comptype, compname))
 
for v in outData:
    # 16-bit,-32767~32767,注意不要溢出
    outwave.writeframes(struct.pack('h',  int(v * 64000 / 2)))
outwave.close()

一些验证:

y, sr = librosa.load(wfile, sr = None)
diff = waveData - y
print(np.sum(diff), np.mean(diff), np.std(diff))
# -6.01820387339325e-05 -1.0419328035653133e-09 3.521011031358344e-06
posted @ 2022-06-11 01:58  Skye_Zhao  阅读(2782)  评论(0编辑  收藏  举报