## Digital signal processing in Scilab and Xcos. Part 2: Playing sound files

In my previous post on DSP in Scilab, I gave an example on how to open a wav file and make it available for further processing.

Today we’ll discuss the opposite task: how to generate signals and store them into wav files.

Open the Scilab’s editor


editor


Choose the sampling rate, the number of bits per sample, and the time duration for your signals


Fs = 11025; // samples per second
bits = 16; // bits per sample
t_total = 10; // seconds


The total number of samples in the signal:


n_samples = Fs * t_total;


Create an array of time points at which the samples will be synthesized:


t = linspace(0, t_total, n_samples);


The following code will generate a 440 Hz sine wave, and save it into a wav file sin440.wav


f=440; // sound frequency

// Sine wave
sin_wave = sin(2*%pi*f*t);
wavwrite(sin_wave, Fs, bits, sin_file);


Let’s now generate a sawtooth wave of the same frequency and output it into another wav file:


// Sawtooth wave
saw_wave=2*(f*t-floor(0.5+f*t));
wavwrite(saw_wave, Fs, bits, saw_file);


Similarly, for a triangle and a square waves:


// Triangle wave
tri_wave=(2/%pi)*asin(sin(2*%pi*f*t));
wavwrite(tri_wave, Fs, bits, tri_file);

// Square wave
sq_wave=sign(sin(2*%pi*f*t));
wavwrite(sq_wave, Fs, bits, sq_file);


Let’s simulate a guitar sound using the Karplus–Strong string synthesis method.


// Karplus-Strong
n_width=100;
ks=-1+2*rand(1,n_width,"uniform");
alpha=0.96;

while ( length(ks) < n_samples )
ks=[ks,alpha*ks($-n_width+1:$)];
end
ks=ks(1:n_samples);


We can play the generated sound in Scilab with


sound(ks)


and plot its waveform


plot(t,ks)


Next: part 3