python对批量WAV音频进行等长分割的方法实现

时间:2022-08-28 19:24:24

对批量WAV音频进行等长分割

对WAV格式的音频以相同长度进行分割。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import os
import wave
import numpy as np
import pylab as plt
import librosa
 
path = r"D:\cutaudio\test"
files = os.listdir(path)
files = [path + "\\" + f for f in files if f.endswith('.wav')]
CutTime = 4 #单位长度4s
 
def CutAudios():
  for i in range(len(files)):
    FileName = files[i]
    f = wave.open(r"" + FileName, 'rb')
    params = f.getparams() #读取音频文件信息
    nchannels, sampwidth, framerate, nframes = params[:4] #声道数, 量化位数, 采样频率, 采样点数 
    str_data = f.readframes(nframes)
    f.close()
    
    wave_data = np.frombuffer(str_data, dtype=np.short)
    #根据声道数对音频进行转换
    if nchannels > 1:
        wave_data.shape = -1, 2
        wave_data = wave_data.T
        temp_data = wave_data.T
    else:
        wave_data = wave_data.T
        temp_data = wave_data.T
 
    CutFrameNum = framerate * CutTime
    Cutnum =nframes/CutFrameNum #音频片段数
    StepNum = int(CutFrameNum)
    StepTotalNum = 0
   
    for j in range(int(Cutnum)):
      FileName = r"D:\cutaudio\11\\" + files[i][-17:-4] +"-"+ str(j) + ".wav"
      temp_dataTemp = temp_data[StepNum * (j):StepNum * (j + 1)]
      StepTotalNum = (j + 1) * StepNum
      temp_dataTemp.shape = 1, -1
      temp_dataTemp = temp_dataTemp.astype(np.short)# 打开WAV文档
      f = wave.open(FileName, 'wb')
      # 配置声道数、量化位数和取样频率
      f.setnchannels(nchannels)
      f.setsampwidth(sampwidth)
      f.setframerate(framerate)
      f.writeframes(temp_dataTemp.tostring()) # 将wav_data转换为二进制数据写入文件
      f.close()
       
if __name__ == '__main__' :
  CutAudios()

到此这篇关于python对批量WAV音频进行等长分割的方法实现的文章就介绍到这了,更多相关python WAV等长分割内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/vitA_gsm/article/details/99756032