from scipy.io import wavfile
import numpy as np
from os import listdir
from ffmpy import FFmpeg as mpy
import os
import shutil
class ConbineSound(object):
"""docstring for ConbineSound"""
def __init__(self,saveName):
super(ConbineSound, self).__init__()
#mp3转换成wav格式的目录,也就是音频拼接的目录
self.wavPath = r'C:\Users\HK\Desktop\语音识别\wav'
#mp3初始文件目录
self.mp3Path = r'C:\Users\HK\Desktop\语音识别\sound2'
#最终合成的音频文件
# self.saveName = r'C:\Users\HK\Desktop\python\代码库\在线字符识别\static\media\result_sound.mp3'
self.saveName = saveName
def combineS(self):
wavs = listdir(self.wavPath)
wavs = sorted(wavs,key=lambda x:int(x.split('.')[0]))
all_sounds = []
for wav in wavs:
file = self.wavPath + '/' + wav
data = wavfile.read(file)
all_sounds.append(data[1][:10 * 14100])
mix = np.concatenate(all_sounds)
wavfile.write(self.saveName, 14100, mix)
# 清空文件夹
def delFiles(self):
# 2.删除文件夹
shutil.rmtree(self.wavPath)
# 3.重新创建文件夹
os.mkdir(self.wavPath)
def trans_to_wav(self,mp3_file, wav_folder):
'''
格式转换格式
:param mp3_file:
:param wav_folder:
:return:
'''
# 格式化文件
file_fmt = os.path.basename(mp3_file).strip()
# 获取文件格式
file_fmt = file_fmt.split('.')[-1]
# 校验文件格式
if file_fmt.strip() != 'mp3':
raise Exception('改文件不是MP3格式,请检查!')
elif file_fmt.strip() == '':
raise Exception('文件格式出现异常,请检查!')
# 创建wav的文件以供转换完成后输出
wav_file_path = os.path.join(wav_folder)
wav_file_path = os.path.join(wav_file_path, '{}.{}'.format(
os.path.basename(mp3_file).strip().split('.')[0], 'wav'
))
# 创建转换时的命令行参数字符串
cmder = '-f wav -ac 1 -ar 16000'
# 创建转换器对象
mpy_obj = mpy(
inputs={
mp3_file: None
},
outputs={
wav_file_path: cmder
}
)
print('执行CMDER 命令:{}'.format(mpy_obj.cmd))
mpy_obj.run()
def read_folder(self):
'''
文件夹读取函数
:param mp3_folder:
:param wav_folder:
:return:
'''
# 遍历需要转换的MP3文件夹中的MP3文件
mp3_folder = self.mp3Path
wav_folder = self.wavPath
for a in os.listdir(mp3_folder):
# 创建MP3文件的绝对路径
mp3_file = os.path.join(mp3_folder, a)
# 调用格式转换函数
self.trans_to_wav(mp3_file, wav_folder)
功能:将某mp3文件进行批量转换成wav格式,然后将wav格式根据文件名(例如:1.wav,2.wav)排序进行拼接。
安装:用到ffmpeg-4.3-win64-static软件,安装之后将D:\ffmpeg-4.3-win64-static\bin添加到环境变量,然后pip install ffmpeg==1.4 ;scipy最好是用1.2.1