wavread error in vibrato function matlab - matlab

I am trying to compile a Vibrato sound effect code that I found on the internet. The code has a function call wavread, in this function matlab is showing error, I've search another codes to do this and every code use this function to open de wav file, someone what is happening? The code below:
Vibrato Script:
clear all;
close all;
clc;
infile = 'musica.wav';
% read in wav sample
[ x, Fs, N ] = wavread(infile);
%set Parameters for vibrato
% Change these to experiment with vibrato
Modfreq = 10; %10 Khz
Width = 0.0008; % 0.8 Milliseconds
% Do vibrato
yvib = vibrato(x, Fs, Modfreq, Width);
% write output wav files
wavwrite(yvib, Fs, 'out_vibrato.wav');
% plot the original and equalised waveforms
figure(1)
hold on
plot(x(1:500),'r');
plot(yvib(1:500),'b');
title('Vibrato First 500 Samples');
Vibrato Function:
% Vibrato
function y=vibrato(x,SAMPLERATE,Modfreq,Width)
ya_alt=0;
Delay=Width; % basic delay of input sample in sec
DELAY=round(Delay*SAMPLERATE); % basic delay in # samples
WIDTH=round(Width*SAMPLERATE); % modulation width in # samples
if WIDTH>DELAY
error('delay greater than basic delay !!!');
return;
end
MODFREQ=Modfreq/SAMPLERATE; % modulation frequency in # samples
LEN=length(x); % # of samples in WAV-file
L=2+DELAY+WIDTH*2; % length of the entire delay
Delayline=zeros(L,1); % memory allocation for delay
y=zeros(size(x)); % memory allocation for output vector
for n=1:(LEN-1)
M=MODFREQ;
MOD=sin(M*2*pi*n);
ZEIGER=1+DELAY+WIDTH*MOD;
i=floor(ZEIGER);
frac=ZEIGER-i;
Delayline=[x(n);Delayline(1:L-1)];
%---Linear Interpolation-----------------------------
y(n,1)=Delayline(i+1)*frac+Delayline(i)*(1-frac);
%---Allpass Interpolation------------------------------
%y(n,1)=(Delayline(i+1)+(1-frac)*Delayline(i)-(1-frac)*ya_alt);
%ya_alt=ya(n,1);
end
The error that appears:
Undefined function or variable 'wavread'.
In the line:
[ x, Fs, N ] = wavread(infile);

The function wavread is not supported since Matlab R2015b.
This functionality has been replaced with audioread, and the prototype has slightly changed.
Please replace the faulty line with
% read in wav sample
[x, Fs] = audioread(infile);
Then the situation is the same with wavwrite that has been replaced with audiowrite.
You should change it to
% write output wav files
audiowrite('out_vibrato.wav', yvib, Fs);

Related

Unrecognized function or variable 'adaptivethreshold'

I am getting the following error message in Matlab "Unrecognized function or variable 'adaptivethreshold'" when every time I want to use Adaptive Threshold function
clear;close all;
im1=imread('page.png');
im2=imread('tshape.png');
bwim1=adaptivethreshold(im1,11,0.03,0);
bwim2=adaptivethreshold(im2,15,0.02,0);
subplot(2,2,1);
imshow(im1);
subplot(2,2,2);
imshow(bwim1);
subplot(2,2,3);
imshow(im2);
subplot(2,2,4);
imshow(bwim2);
those coding from
https://www.mathworks.com/matlabcentral/fileexchange/8647-local-adaptive-thresholding
You should open MATLAB editor inside a folder containing all files: adaptivethreshold.m, page.png, testadaptivethreshold.m, tshape.png and run your script testadaptivethreshold.
Or, you can copy-paste the function definition below the script as follows and make sure also that the images are in the same folder or MATLAB search path.
clear;close all;
im1=imread('page.png');
im2=imread('tshape.png');
bwim1=adaptivethreshold(im1,11,0.03,0);
bwim2=adaptivethreshold(im2,15,0.02,0);
subplot(2,2,1);
imshow(im1);
subplot(2,2,2);
imshow(bwim1);
subplot(2,2,3);
imshow(im2);
subplot(2,2,4);
imshow(bwim2);
function bw=adaptivethreshold(IM,ws,C,tm)
%ADAPTIVETHRESHOLD An adaptive thresholding algorithm that seperates the
%foreground from the background with nonuniform illumination.
% bw=adaptivethreshold(IM,ws,C) outputs a binary image bw with the local
% threshold mean-C or median-C to the image IM.
% ws is the local window size.
% tm is 0 or 1, a switch between mean and median. tm=0 mean(default); tm=1 median.
%
% Contributed by Guanglei Xiong (xgl99#mails.tsinghua.edu.cn)
% at Tsinghua University, Beijing, China.
%
% For more information, please see
% http://homepages.inf.ed.ac.uk/rbf/HIPR2/adpthrsh.htm
if (nargin<3)
error('You must provide the image IM, the window size ws, and C.');
elseif (nargin==3)
tm=0;
elseif (tm~=0 && tm~=1)
error('tm must be 0 or 1.');
end
IM=mat2gray(IM);
if tm==0
mIM=imfilter(IM,fspecial('average',ws),'replicate');
else
mIM=medfilt2(IM,[ws ws]);
end
sIM=mIM-IM-C;
bw=imbinarize(sIM,0);
bw=imcomplement(bw);
end
And here is how it shows the output:

I am using MATLAB HDL coder to convert matlab coder and currently having some error

I am not able to get this error removed. Can someone please help me. The problem is it is showing some error in step 4 while generation of hdl code.
function [Rxx]=autom(X) % [Rxx]=autom(x)
Rxx=zeros(1,1024);
for m=1: 1025
for n=1: 1025-m
Rxx(m)=Rxx(m)+X(n)*X(n+m-1);
end
end
%testbench
N=1024; % Number of samples
f1=1; % Frequency of the sinewave
FS=200; % Sampling Frequency
n=0:1023; % Sample index numbers
X=zeros(1,1024);
% X=sin(2*pi*1*(0:1023)/200);
X=sin((2*pi*1.*n)./200);
t=[1:1024]*(1/200);
%ti=f1*n/FS;
%x=sin(2*pi*ti); % Generate the signal, x(n)
%t1=[1:N];
%t=t1*(1/FS); % Prepare a time axis
subplot(2,1,1); % Prepare the figure
plot(t,X);
title('Sinwave of frequency 1000Hz [FS=8000Hz]');
xlabel('Time, [s]');
ylabel('Amplitude');
grid;
Rxx = autom(X(1:1024)); % Calculate its autocorrelation
subplot(2,1,2);
plot(Rxx);
title('Autocorrelation function of the sinewave'); % Plot the autocorrelation
xlabel('lags');
ylabel('Autocorrelation');
The error says: "[...] unsuported dynamic matrix X[...]"
Your problem is that in your function you are doing X(n)*X(n+m-1); and it seem to be understanding that this is dynamically changing the size of the matrix. I suspect in fact that the error is in Rxx
Note that your X is 1024 on length, but your iterations of n and m are 1025 in length. Rxx is 1024 on length, but you do Rxx(m) and m goes up to 1025, thus dynamically changing its size (MATLAB will increase the size of Rxx from 1024 to 1025, dynamically)
Are you sure you dont want
function [Rxx]=autom(X) % [Rxx]=autom(x)
Rxx=zeros(1,1024);
for m=1: 1024
for n=1: 1024-m
Rxx(m)=Rxx(m)+X(n)*X(n+m-1);
end
end

Separating audio file in 3 different frequency areas

I apologize in advance, if the title is confusing. Basically, i have a Audio-file, on which I perform a STFT every 50ms. My File is about 11 seconds long (10.8526s), which i have cut off from a soundtrack. Btw, i am not allowed to use the built-in function in Matlab for the STFT. I am aware it is much more easier. Anyway, after i run my code, every 50 ms a STFT is performed and the picture is being plotted.
Now i want to seperate it in 3 different plots. In the first plot i have the lower frequencies (0-300Hz), in the second plot medium frequencies(300-5kHz) and in the last plot i have high frequencies(5Khz-fs/2). fs=44100 --> Further explanations below in the code. How can i define now the areas?
%AUDIO-FILE
%______________________________________________________
[y,fs]=audioread('UnchainMyHeart.wav');
% audioread = Reads Audio file
% y = A vector, which contains the audio signal
% fs = sample rate
% 'UnchainMyHeart' = Audio file
%______________________________________________________
% Paramter for the real-time spectral-analysis
%______________________________________________________
NFA=2;
% Every second picture is being plotted
% Don't need every picture
t_seg=0.05;
%Length of the audio signal on which is a STFT performed
fftlen = 4096;
% Length of the FFT, frequency resolution
TPF= 300;
BPF= 5000;
HPF= 22050;
% Trying to define the frequencies areas
% Isn't working right now
LOW=((TPF*fftlen)/fs);
MEDIUM=((BPF*fftlen)/fs);
HIGH=((HPF*fftlen)/fs);
% Contains the number of FFT points in the frequency
%_______________________________________________________
segl =floor(t_seg*fs);
windowshift=segl/2;
window=hann(segl);
window=window.';
si=1;
% Start Index
ei=segl;
% End Index
AOS= length(y)/windowshift - 1;
f1=figure;
f=0:1:fftlen-1;
f=f/(fftlen-1)*fs;
Ya=zeros(1,fftlen);
n=0;
for m= 1:1:AOS
y_a = y(si:ei);
y_a= y_a.*window;
Ya=fft(y_a, fftlen);
n=n+1;
if n==1
Yres=abs(Ya);
else
Yres=Yres+abs(Ya);
end
if n==NFA
Yres=Yres/NFA;
n=0;
drawnow;
%Updates the graphical objects which are being plotted every 50ms
figure(f1);
plot(f(1:end/2), 20*log10(abs(Yres(1:end/2))));
ylim([-90 50]);
title('Spektrum of audio signal');
xlabel('f(Hz)');
ylabel('dB');
grid on;
end
si=si+windowshift;
% Updating Start Index
ei=ei+windowshift;
% Updating End index
end
I am not able to run you code as I do not have your audio file but I will try to explain conceptually, and use pseudo code.
Frequency brick-wall
If you just want to separate the frequencies for visual purposes you can just use brick-wall filters.
Perform an fft of the full signal. Define a frequency vector.
SigFD = fft(signal);
n = length(signal); % number of samples
fs = 44100; % sampling rate
deltaF = fs/n; % frequency resolution
F = [0:floor(n/2)-1, -(floor(n/2)):-1]*deltaF; % frequency vector
Slice the signal based on the frequency range that you want.
lowF = 0;
highF = 500;
part1Range = abs(F)>lowF&abs(F)<highF;
Fpart1 = F(part1Range);
Sig1FD = SigFD(part1Range);
Note that I am unable to test the code on your waveform so this should be considered more of pseudo code!

How to do a frequency band?

Here in this code i am doing a stft on my wav-file. There is no problem with that. At the beginning, i am defining my parameter, afterwards using my wav file and then applying the stft. Basically what i am doing is a real-time spectral analysis. Anyway my question is, how do i a frequency band? I want my signal to be separated in LOW/MEDIUM/HIGH. I want my vector to be saved, from 0-250 Hz in the LOW-Band, 250-5000 Hz in the MEDIUM-Band, 5-22.05k Hz in the HIGH-Band. I advise you, to try my code in Matlab, if you don't understand it. Just take any wav-file. Btw my signal is plotted in the variable "Yres". Any solution is appreciated!
NFA=2; % Number is used for plotting every 2nd picture
t_seg=0.05; % Length of segment in ms
fftlen = 4096;
% Lenght of "fft",because our segment contains 2205 points
[y,fs]=audioread('UnchainMyHeart.wav');
% audioread = functions reads WAV-file
% y = A vector which contains my audio signal
% fs = sample frequency (44100)
% 'UnchainMyHeart' = WAV-file
t=linspace(0,length(y)/fs,length(y));
% linspace = Creating time vector
% 0 = Start time
% length(y)/fs = End time
% length(y) = Number of samples in y
plot(t,y)
% plotting signal in the time domain
segl =floor(t_seg*fs);
% Applying fft function on the variable "segl"
windowshift=segl/2;
% Defining the size of the window, which goes to the next "segl"
window=hann(segl);
% hann function
window=window.';
si=1;
%Start index
ei=segl;
%End index
AOS= length(y)/windowshift - 1;
% AOS is the number of "segl" we use (About 433)
f1=figure;
% Opening new window
f=0:1:fftlen-1;
f=f/(fftlen-1)*fs;
% Defining frequency vector
Ya=zeros(1,fftlen);
plot(f,Ya),axis([0 fs -90 50])
grid on
n=0;
%start variable
for m= 1:1:AOS
y_a = y(si:ei);
y_a= y_a.*window;
Ya=fft(y_a, fftlen);
n=n+1;
if n==1
Yres=abs(Ya);
else
Yres=Yres+abs(Ya);
end
if n==NFA
Yres=Yres/NFA;
n=0;
drawnow;
%Tut die Grafikobjekte immer auf den neuesten Stand updaten
figure(f1);
plot(f(1:end/2), 20*log10(abs(Yres(1:end/2))));
ylim([-90 50]);
title('Spektrum eines Audiosignal');
xlabel('f(Hz)');
ylabel('dB');
grid on;
end
si=si+windowshift;
% Updating start index
ei=ei+windowshift;
% Updating end index
end
This may not be the best answer! But this may help you get started on something. You can use spectrogram() function from MATLAB's Signal Processing Toolbox.
Let's suppose you have an audio file named ''UnchainMyHeart.wav'(in your case) with one channel. The code goes as follows:
% Reading the audio file
[y1,fs] = audioread('UnchainMyHeart.wav');
% Parameters for STFT (or spectrogram)
windowDuration = 30e-3; overlapDuration = 15e-3;
windowLength = round(windowDuration*fs); % window length
overlapLength = round(overlapDuration*fs); % overlapping of windows
nfft = 1024;
% Executing STFT for the signal
[S1,F1,T1,P1] = spectrogram(x1,hanning(windowLength), ...
overlapLength, nfft, fs, 'yaxis');
S1 and P1 contain STFT and Power Spectrum Density(PSD) of the signal for a time interval of each section with a time interval whose estimations are contained in T1.
For your question, you are looking for F1 which is a vector of cyclical frequencies expressed in terms of sampling frequency, fs. For example: if you have a sampling frequency of 48 kHz (fs) and nfft of 1024, then you will have 513 [(1024/2) +1)] frequency values spaced by (fs/nfft). i.e. 46.875. So your frequency components will be 0, 46.875, 46.875*2, ..., 46.875*512. The maximum you will have is 24 kHz due to Nyquist criterion.
Now, you can easily write a simple routine specifying the ranges as you said. The same technique can be used in your code which is an implementation of stft. I would suggest using MATLAB's built-in function unless your problem requires an implementation. Hope this helps!
If needed, I can answer why the parameters for STFT are chosen as included in the code.

How do I get backpropagation to work for a MLP? MATLAB

I am trying to get an MLP to work. My goal is to get the net to predict output Yt when given Yt-1,Yt-2...,Yt-10. I've been using a generated dataset, which should be no trouble. My net will always output a straight line and will shift that line up and down. The line is always flat everywhere, it does not start to curve. My target is a portion of a sin(x) curve.
This is my code:
Dataset:
% Underlying function
syms f(a)
f(a)=sin(a/50);
% Data: lagged
x=[1:100+10]';
% add noise
y=eval(f(x))+0.01*randn(numel(x),1);
% rescale dataset to [0,1]
y=(y-min(y))/(max(y)-min(y));
% Lagged predictor
X=[];
for L=1:10
temp=lagmatrix(y,-L);
X=horzcat(X,temp);
end
% train set size m
y_training=y(1:100);
X_training=X(1:100,:);
Training:
%% Network
% Initialize weights
W1=randn(10,10)/10; Wb1=randn(10,1)/10;
W2=randn(10,10)/10; Wb2=randn(10,1)/10;
W3=randn(1,10)/10; Wb3=randn(1,1)/10;
% Activation function
syms f(z);
f(z)=1/(1+exp(-z));
Df=diff(f);
% Net parameters
alpha=3;
lambda=0;
costs=[];
m=numel(y_training); % size of training set
no_iter=500; % number of iterations of grad descent
p=1;
for j=1:no_iter
%Initialize error
deltaW1=zeros(size(W1)); deltaWb1=zeros(size(Wb1));
deltaW2=zeros(size(W2)); deltaWb2=zeros(size(Wb2));
deltaW3=zeros(size(W3)); deltaWb3=zeros(size(Wb3));
JW=0;
keep_output=[];
for i=1:m
% input layer
a1=[X_training(i,:)']; y_true=y_training(i);
% FP activations
z2=[W1 Wb1]*[a1; 1]; a2=eval(f(z2));
z3=[W2 Wb2]*[a2; 1]; a3=eval(f(z3));
z4=[W3 Wb3]*[a3; 1]; a4=eval(f(z4));
% BP individual errors
delta_a4= -(y_true-a4) .* eval(Df(z4));
delta_a3= W3'*delta_a4 .* eval(Df(z3));
delta_a2= W2'*delta_a3 .* eval(Df(z2));
% DJDW for each parameter
DJDW3=delta_a4*(a3)'; DJDWb3=delta_a4;
DJDW2=delta_a3*(a2)'; DJDWb2=delta_a3;
DJDW1=delta_a2*(a1)'; DJDWb1=delta_a2;
% summing DJDW of each example
deltaW1=deltaW1+DJDW1; deltaWb1=deltaWb1+DJDWb1;
deltaW2=deltaW2+DJDW2; deltaWb2=deltaWb2+DJDWb2;
deltaW3=deltaW3+DJDW3; deltaWb3=deltaWb3+DJDWb3;
% Cost function
JW_xy=(y_true-a4)^2; % single example
JW=JW+JW_xy; % aggregate
% store output and true values
keep_output=[keep_output a4];
end
% update weights according to average cost of current iteration
W1=W1-alpha*( (1/m)*deltaW1) ; Wb1=Wb1-alpha*( (1/m)*deltaWb1);
W2=W2-alpha*( (1/m)*deltaW2) ; Wb2=Wb2-alpha*( (1/m)*deltaWb2);
W3=W3-alpha*( (1/m)*deltaW3) ; Wb3=Wb3-alpha*( (1/m)*deltaWb3);
clf, plot(y_training), hold on
plot(keep_output);
drawnow
end
It only seemed that the backpropagation algorithm wasn't working. What I observed was a line shifting up and down with each iteration. The problem was I wasn't scaling the output.
Given that I scaled the input dataset, the output should also be scaled.