Python对wav文件的重采样实例
例如从2channel,4.41khz重采样到1channel,16khz
defdownsampleWav(src,dst,inrate=44100,outrate=16000,inchannels=2,outchannels=1): importos,wave,audioop ifnotos.path.exists(src): print('Sourcenotfound!') returnFalse ifnotos.path.exists(os.path.dirname(dst)): os.makedirs(os.path.dirname(dst)) try: s_read=wave.open(src,'r') s_write=wave.open(dst,'w') except: print('Failedtoopenfiles!') returnFalse n_frames=s_read.getnframes() data=s_read.readframes(n_frames) try: converted=audioop.ratecv(data,2,inchannels,inrate,outrate,None) ifoutchannels==1: converted=audioop.tomono(converted[0],2,1,0) except: print('Failedtodownsamplewav') returnFalse try: s_write.setparams((outchannels,2,outrate,0,'NONE','Uncompressed')) s_write.writeframes(converted) except: print('Failedtowritewav') returnFalse try: s_read.close() s_write.close() except: print('Failedtoclosewavfiles') returnFalse returnTrue
若in和out都是单通道:
defdownsampleWav(src,dst,inrate=48000,outrate=16000,inchannels=1,outchannels=1): importos,wave,audioop ifnotos.path.exists(src): print('Sourcenotfound!') returnFalse ifnotos.path.exists(os.path.dirname(dst)): os.makedirs(os.path.dirname(dst)) try: s_read=wave.open(src,'rb') params=s_read.getparams() nchannels,sampwidth,framerate,nframes=params[:4] print(nchannels,sampwidth,framerate,nframes) s_write=wave.open(dst,'wb') except: print('Failedtoopenfiles!') returnFalse n_frames=s_read.getnframes() data=s_read.readframes(n_frames) try: converted=audioop.ratecv(data,2,inchannels,inrate,outrate,None) ifoutchannels==1andinchannels!=1: converted=audioop.tomono(converted[0],2,1,0) except: print('Failedtodownsamplewav') returnFalse try: s_write.setparams((outchannels,2,outrate,0,'NONE','Uncompressed')) s_write.writeframes(converted[0]) exceptExceptionase: print(e) print('Failedtowritewav') returnFalse try: s_read.close() s_write.close() except: print('Failedtoclosewavfiles') returnFalse returnTrue
方案二
y为下采样的结果,类型np.ndarray
YoucanuseLibrosa'sload()function,
importlibrosa
y,s=librosa.load('test.wav',sr=8000)#Downsample44.1kHzto8kHz
TheextraefforttoinstallLibrosaisprobablyworththepeaceofmind.
Pro-tip:wheninstallingLibrosaonAnaconda,youneedtoinstallffmpegaswell,so
pipinstalllibrosa
condainstall-cconda-forgeffmpeg
以上这篇Python对wav文件的重采样实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。