求.wav.mp3音频里一分钟平均响度(分贝),存在csv中

环境需要有包pudub,ffmpeg,pyaudio
并下载ffmpeg 放在文件目录中,url:https://ffmpeg.zeranoe.com/builds

import wave
import math
import pyaudio
import numpy
import pandas as pd
import os
from pydub import AudioSegment

#求数组平均值
def mean(a):
    return numpy.longlong(sum(a)) / len(a)

#把mp3格式转化为.wav模式
def trans_mp3_2_wav(filename):
    name = os.path.splitext(filename)[0]
    audio=AudioSegment.from_mp3(filename)
    audio.export(name + ".wav",format="wav")

#绝对值函数
def abslist(a):
    return list(map(abs,a))

def recvoice(filename):
    #取文件名
    name = os.path.splitext(filename)[0]
    #打开WAV文档,文件路径根据需要做修改
    wf = wave.open(name + ".wav", "rb")
    #创建PyAudio对象
    p = pyaudio.PyAudio()
    stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),channels=wf.getnchannels(),rate=wf.getframerate(),output=True)
    nframes = wf.getnframes()
    framerate = wf.getframerate()
    #读取完整的帧数据到str_data中,这是一个string类型的数据
    str_data = wf.readframes(nframes)
    wf.close()
    #将波形数据转换为数组
    wave_data = numpy.fromstring(str_data, dtype=numpy.short)
    #wave_data=list(map(abs,wave_data))
    M = []
    #求60秒取样的平均值,若为双声道,再多乘2
    n = framerate*60
    for i in range(0, len(wave_data), n):
         M.append(wave_data[i:i+n]/10) #传化成分贝
    M=map(abslist,M)
    sound = list(map(mean,M))
    #时间数组,与sound配对形成系列点坐标
    time = numpy.arange(0,nframes/(60 *framerate))
    time = time.astype(int) * 60
    #生成csv文件
    dataframe = pd.DataFrame({'Time(s)':time,'Sound':sound})
    dataframe.to_csv( name + ".csv",index=False,sep=',')

#获取文件目录下的mp3 wav格式音频
def file_name(file_dir):
    L=[]
    for root, dirs,files in os.walk(file_dir):
        for file in files:
            #.mp3格式转化为.wav
            if os.path.splitext(file)[1] == '.mp3': 
                trans_mp3_2_wav(os.path.join(root, file))
                print(file)
                L.append(os.path.join(root, file))
            if os.path.splitext(file)[1] == '.wav':
                L.append(os.path.join(root, file))
    for i in range(len(L)):
        print(L[i])
        recvoice(L[i])

if __name__== "__main__":
    file_name("//文件路径")

你可能感兴趣的:(编码)