完整代码在这里
len=2048;
semilen=len/2;
[filename,path]=uigetfile('*.wav','please select a wave file'); % read a wave file 打开音频文件
tic;
filename=strcat(path,filename); %得到音乐文件名
[data,fs]=wavread(filename); %读取音乐b
r=frame(len,semilen,data);
s=size(r,1);
r=r';
for i=1:s
r_fft(:,i)=abs(fft(r(:,i)));
r_window(:,i)=r_fft(:,i).*hamming(len);
end
for i=1:s
if i==1;
delta_r(:,i)=r_fft(:,i);
end
if i==2;
delta_r(:,i)=r_fft(:,i)-2*r_fft(:,i-1);
end
if i>=3;
delta_r(:,i)=r_fft(:,i)-2*r_fft(:,i-1)+r_fft(:,i-2);
end
end
for i=1:s
if i==1;
delta_r_two(:,i)=r_fft(:,i);
end
if i>=2;
delta_r_two(:,i)=r_fft(:,i)-r_fft(:,i-1);
end
end
for i=1:s
Dpd_r(:,i)=mean(abs(delta_r(:,i))+abs(delta_r_two(:,i)));
end
maxDpd_r=max(Dpd_r);
normalDpd_r=Dpd_r/maxDpd_r;
for i=1:s
if i==1;
ThersDpd_r(:,i)=mean(normalDpd_r(i)+normalDpd_r(i+1));
end
if i==s;
ThersDpd_r(:,i)=mean(normalDpd_r(i-1)+normalDpd_r(i));
end
if i>=2&&i<=s-1;
ThersDpd_r(:,i)=(normalDpd_r(i-1)+normalDpd_r(i)+normalDpd_r(i+1))/3;
end
end
for i=1:s
if normalDpd_r(i)-ThersDpd_r(i)>0;
Decide_Dpd_r(i)=Dpd_r(i);
end
if normalDpd_r(i)-ThersDpd_r(i)<=0;
Decide_Dpd_r(i)=0;
end
end
q=imregionalmax(Decide_Dpd_r);
q=double(q);
for i=1:length(q)
onset((i-1)*semilen+1)=q(i);
end
n=min(length(data),length(onset));
for i=1:n
oridata(i)=data(i);
orionset(i)=onset(i);
end
stem(orionset,'r');
hold on;
plot(oridata);
toc