【深度學習資料預處理2】使用Matlab批量生成聲譜圖
阿新 • • 發佈:2019-01-07
接上篇裁剪音樂檔案。給深度學習做資料準備,通過Matlab生成聲譜圖。
function cut_wavs(file_dir,output_dir,t,t_overlap)
files=dir(file_dir);
count=0;
for i =3:length(files)
if ~exist(output_dir)
mkdir(output_dir);
end
count=i-2;
if files(i).isdir
temp_dir=file_dir;
now_dir=strcat(temp_dir,'/' ,files(i).name);
now_output_dir=strcat(output_dir,'/',files(i).name);
cut_wavs(now_dir,now_output_dir,t,t_overlap);
clear temp_dir;
elseif files(i).name(end-2:end)=='wav'
wavfile_name_new = strcat(file_dir,'/', files(i).name);
[y,fs]=audioread(wavfile_name_new);%讀取音樂數值與引數
last_time=length(y)/fs;%時長
num=fix((last_time-t)/t_overlap+1);%切割後音樂的份數
for k=1:num%對每首音樂進行切割並命名
starttime=(k-1)*t_overlap;
endtime=(k-1)*t_overlap+t;
y_out=y(starttime*fs+1:endtime*fs+1,:);
filename=strcat(output_dir,'/' ,num2str(count),'-',num2str(k),'.wav');
%-----------------------------------------------------------------------------
%以上程式碼與前一篇相同,這裡加了一個判斷,
%以防同一個資料夾裡有單雙聲道的檔案同時存在
[m,n] = size(y);
try %昨天遇到了原因不明的bug,可能是原始檔損壞導致,加入try迴圈避開
if n>1
%雙聲道情況
y_out=y(starttime*fs+1:endtime*fs+1,:);
%左聲道
y_l=y_out(:,1);
%右聲道
y_r=y_out(:,2);
%立體聲
y_m=(y_l+y_r)./max(max(y_out));
%attentions=strcat('Saving...',filename)
%audiowrite(strcat(filename(1:end-3),'_l.wav'),y_l,fs);
else
%單聲道情況
y_m=y(starttime*fs+1:endtime*fs+1);
%註釋掉儲存音樂片段的程式碼,改成生成頻譜圖的程式碼
else
y_m=y_out;
end
R=1024;%設定窗函式長度
window=hamming(R);%使用漢明窗
N=1024;%短時傅立葉函式點數
L=512;%步長
overlap=R-L;%窗重疊點數
figure('visible','off')
%x= awgn(x,100,'measured','linear');
% x= x(1:3.2:end,1); %如需要對於音樂取樣呼叫該函式
[S,F,T]=spectrogram(y_m,window,overlap);%生成聲譜圖
spec=20*log10(abs(S)+eps);
axis off;%關閉座標
imagesc(spec);
%把矩陣繪製成圖時呼叫,imagesc(A) 將矩陣A中的元素數值按大小轉化為不同顏色。
%如需灰度請呼叫colarmap grey
set(gcf,'position',[0,0,200,200]);
%設定 figure 的位置和大小,此處大小為 200x200
set(gca,'position',[0 0 1 1]);%去掉邊框,不去掉儲存會有一圈灰色的
f=getframe(gcf); %直接儲存為聲譜彩圖,大小由上面呢引數決定
formatSpec = 'Saving.. src_dir %s..dst_dir %s..all
progress %0.2f%%..single progress %0.2f%%.. \n';
fprintf(formatSpec,file_dir,output_dir,
count/length(files)*100,k/num*100)
imwrite(f.cdata,strcat(filename(1:end-4),'.jpg'),'jpg');
%imwrite(y,str2,'jpg');
%如需要對聲譜圖矩陣進行處理,需要使用該函式儲存
close(gcf);
end
end
end
end
end
執行時和上一篇一樣,儲存以上檔案,在同一個資料夾新建指令碼使用上面的函式,如下圖:
結果如下:
生成圖片如下: