Sie sind auf Seite 1von 6

Lab 2: More MATLAB and Working with Sounds

EE299 Winter 2008


Due: In lab, on or before 25 January 2008.
You will need: an EE computer account for accessing the web server, and a pair of headphones for
listening to sounds.
Objective
In this lab, you will learn a few more skills in MATLAB. In the following sections, we cover:
Use of M-les and for loops in MATLAB
Building sounds from sinusoids
Reading, writing and recording sounds
Use MATLAB commands to display the frequency content of signals.
The TA will pick dierent people to run the M-les that you create in this lab. You can work together to
implement them, and dierent people can work on dierent aspects of the lab, but you will each need to be
able to demonstrate any of the parts and answer questions about them.
Prelab
If you do not already have an EE computer account, you will need to get one. See
https://www.ee.washington.edu/computing/faq/new account.html
for more information. It is a good idea to do this at least a day before your lab, so that there is time to
resolve any problems should they arise.
One of the exercises that you will do is to synthesize a short sequence of notes from some song. For
this part of the lab, you should gure out your song ahead of time, and get a musical score with the basic
notes and their lengths (whole, quarter, etc.). While you can do chords if you want to be more ambitious,
but you are not required to, and you should plan on a simple single-note-at-a-time version for your rst
implementation to simplify script debugging.
In addition, you will be recording some sound in the lab. If if you do not want to record your own voice,
you might want to bring some sort of musical instrument or noisemaker to record. Pick something that will
have frequency content that changes as a function of time.
1 Introduction to MATLAB (Part II)
In this part we cover a few more features in MATLAB. You will learn how to write scripts in MATLAB use
M-les, and the basic programming concept of for loops. You will use these together to create a simple song
with sinusoids.
1
1.1 For Loops
In this section we will cover a basic programming tool: for is used to tell MATLAB to do the same set
of statements multiple times. If you are familiar with this concept from other programming languages this
section should be easy, because the concepts are the same in MATLABjust the syntax may be dierent.
The general form for for loops is:
for variable = startingvalue : stepsize : endingvalue
. . . some MATLAB statements . . .
end
At the beginning of the rst loop, variable is set to startingvalue, and at the beginning of every subsequent
loop, variable has stepsize added to it. Each time through the loop, the statements in the middle are
executed. The loop stops when the new value of variable would be greater than endingvalue. If stepsize is
left out, the default value of 1 is used. (See the MATLAB help function for more information.)
Consider this simple MATLAB code:
z=0;
for n=1:10
z=z+n;
end
The rst line assigns the value 0 to the variable z. Then the for loop begins: the variable n is set to the
rst value 1. The single line within the for loop sets z to z+n, so on the rst time through the loop z will
be set to 0 + 1 = 1. At the beginning of the next loop, the value of n is increased by 1 and the line within
the loop is executed again with the new values of z and n,i.e. 1+2=3. The nal loop occurs when n=10;
then it stops. The MATLAB function sum(x), if x is a vector, adds all the elements in the vector x. Check
the denition of the sum function in MATLAB help, and verify for yourself that the MATLAB code above
is equivalent to z=sum(1:10).
Another example of a for loop is:
A=-5:5;
L=length(A);
for i=1:L
B(i)=A(L+1-i);
end
What is the relationship between the resulting vector B and A? Verify for yourself that the same eect could
be accomplished using the B=fliplr(A) operation in MATLAB.
1.2 M-les
As you learned in Lab 1, you can use MATLAB interactively by typing commands in the Command Window,
and having MATLAB execute them one at a time. Another way to use MATLAB is to create a le containing
a sequence of commands, called an M-le (its lename will end in .m), and run all the commands in the
M-le at the end. M-les are very useful when the task you want to do requires several commands, since
it saves work typing things in when you make a mistake. M-les can be saved, so they can be run multiple
times and easily changed if you want to do some step dierently. Another reason is that for larger projects,
its good to divide up your task into smaller pieces and M-les make this easier.
There are actually two types of M-les: scripts and functions. We will learn about scripts in this lab,
and functions in the next lab.
A script is just a sequence of MATLAB commands, like those that you would type into the Command
Window. MATLAB runs the commands in the M-le in order, as if they were typed into the Command
Window. You can run an existing script if it is in your working directory. Try downloading the beethoven.m
script
1
from the class web page, editing, and running that. Well step you through it here, but you may
want to see the document Using MATLAB for EE students (linked on the class webpage) for more details
1
The idea of synthesizing Beethovens Fifth is due to Virginia Stonick.
2
about creating folders, saving and uploading M-les, as well as several other details about using MATLAB
in the EE computer labs.
Create a new folder named Lab 2. This folder can be anywhere on your computer. The M-les that
you make in this lab will be kept temporarily in this folder, but you will need to save them somewhere
permanent, like your home directory (EE account) when you are done. If there is already a Lab 2 folder
on the desktop, it could be from the other section or another course, so better to just use a dierent directory
or new name to make sure you dont accidentally use someone elses M-les.
Move the beethoven.m le to this folder. Change the MATLAB Current Directory to the Lab 2
folder (or whatever you called it): at the top of the MATLAB screen, click on the ... button (browse for
folder) next to the Current Directory label. See Figure 1. Then select the desired folder and click ok. One
way to run the script is to simply type the name of the le (e.g. beethoven not beethoven.m) in the
Command window. Try it. If you are in the folder with the correct M-le, you should here a short sequence
of notes from Beethovens 5th.
To start a new M-le, you can again click on the le pulldown menu button but then go to new and
then to M-le, or theres a shortcut open blank M-le icon you can click on, shown in Figure 1. This
will open up the MATLAB editor. To edit an existing M-le, you can click on its name in the list of les for
the current directory panel, click on the le pulldown menu button in the upper right of the MATLAB
window and then go to open, or click on the open le icon in the upper right of the MATLAB window
(next to the open blank M-le icon).

Open blank M-file Browse to select new Current Directory




Figure 1: Change the Current Directory to your Lab 2 folder; open a blank M-le for editing by clicking on
the white page icon on the top left of the MATLAB window.
The process you will follow to construct scripts is:
1: Open a blank M-le and add the commands you want in the order you want them to be executed,or
you can start from an existing M-le.
2: Save and run the M-le.
3: Make any changes to the commands in the M-le if it does not run because of a syntax error, or does
not do exactly what you want. (Note: sometimes the error is that you are in the wrong directory, not
that your M-le has a problem. Check that when the error message says that a le is not found.)
4: Repeat steps 2 and 3 until you have an M-le that does what you want.
3
Note that M-les can contain commands that correspond to other M-les.
Open the beethoven.m script in the MATLAB editor. In this le, the text that starts with a % is
called a comment. Comments are used to tell yourself or someone else what your code does. They are
not MATLAB commands and get ignored by MATLAB, so they do not aect the way your le runs. Try
changing something in the beethoven.m le so that it sounds a little dierent (e.g. dierent length notes or
pauses). Reading the comments should be helpful.
When you are editing an M-le, you can run it by either clicking on the run icon at the top of the
open M-le, or by typing the name of the le (without the .m part) into the Command Window. (You can
also run an M-le by typing the name of the le in another M-le, and then running the other M-le.) Note
that the M-le does not need to be open for editing in order for you to run it.
2 Making Sounds from Sinusoids
2.1 A Simple Synthesizer
The simplest synthesizer creates a note from just one sinusoid, as in the Beethoven example. Go back to the
beethoven.m script in the MATLAB editor. You should notice that the M-le includes for loops to repeat
the same note. It also concatenates sounds (builds longer vectors) by using the command:
signal = [signal XXX];
where XXX is either a sequence of zeroes to create a short silent region or a sequence generated by a
cosine. Note that the command zeros(1,200) gives 200 zeros, which corresponds to a silence of duration
25ms since the sampling rate is 8kHz.
Use the ideas in this example to create your own snippet of a song. You can either start from scratch
or edit this le, but save it with a dierent name, e.g. mysong.m. Dont forget the semicolon at the end
of each command, since you will otherwise get big matrices printing out in the command window when you
run the M-le.
To get the frequencies of the notes in your song, you may want to consult:
http://www.phy.mtu.edu/~suits/notefreqs.html -- a table of notes and their frequencies
http://en.wikipedia.org/wiki/Note -- a general formula for computing note frequencies
You should start with a song that has just a single note sequence to make it easier to be sure your script
is working. Optionally, if you want to have chords, you can simply add two notes together (e.g. chord =
note1 + note2 in MATLAB if note1 and note2 are of the same length).
When you are happy with your song, add a line to the script to write out an audio le so that you can
play it back later without the script. If you use the same signal and sampling frequency variable names as
in the beethoven script, then the command could be:
>> wavwrite(signal,Fs,mysong)
which would create a le mysong.wav in your working directory.
Run your new M-le for your TA by clicking on the run icon at the top of the M-le
editor. Submit the M-le and associated audio le to the CollectIt drop box for Lab 2.
2.2 More Natural Notes
The time representation describes a signal in terms of how the amplitude changes as a function of time:
x(t) is the amplitude of the signal at time t. Transforms characterize a complex signal as a weighted sum
of simple signals. When we talk about describing a time signal in the frequency domain, were using one
particular transform, the Fourier transform. The Fourier transform uses sinusoids of dierent frequencies as
4
the simple signals: X(f) describes the amplitude A(f) and phase (f) of the cosine of frequency f used to
build the signal. For periodic signals (as in the musical instrument notes), the signal is built by:
x(t) =

k
A
k
cos(2f
k
t +
k
) =

k
A
k
cos(2kf
0
t +
k
)
where f
0
is the fundamental frequency and f
k
= kf
0
are the harmonics. (We use the k subscript instead of
the argument f, as in A
k
vs. A(f
k
), for brevity.) Note that we will not be worrying about the phase terms
in this lab. Next, well create a synthetic horn note, progressively making it sound more like the original by
adding in more harmonics.
For this part of the lab, you will need to download the soundle horn11short.wav and the M-les
getfreqs.m, cosgen.m and cosgen.g and move them to your working directory. The cosgen tool will allow
you to look at the time and frequency representations side by side (time is on the left, frequency is on the
right). The time window shows only a short duration of the actual signal, so that the changes are more
visible as you add more cosines. The getfreqs command will allow you to measure the frequency and
amplitude of the cosines in a sound (phase is not shown).
Create a synthetic horn note by:
1. Use cosgen to look at a natural horn sound (load horn11short.wav) and play the signal.
2. Use getfreqs to measure the amplitude and frequency of the cosines in that sound.
3. Use cosgen a second time to create a synthetic horn sound by adding up cosines with the amplitudes
and frequencies measured. Save the synthetic sound at each step of adding a cosine, using the save
button in cosgen and specifying dierent names like 1cos, 2cos, etc.
4. Play the natural and synthetic examples to determine how many cosines you need before it starts
sounding like the natural horn.
To play the notes back and forth, read them into MATLAB and play them using the wavread and sound
commands, as follows:
>> [note1, fs]=wavread(1cos);
>> [note2, fs]=wavread(2cos);
>> ...
>> [natural, fsn]=wavread(horn11short);
>> sound(note1,fs)
>> sound(natural,fsn)
>> sound(note2,fs)
>> sound(natural,fsn)
>> ...
The fs and fsn are the sampling frequencies of the sounds. All the synthetic notes will have the same
sampling frequency, but the natural one is dierent. You need to be careful to use the right sampling
frequency in playing the sound, or it will have the wrong pitch.
3 Time-Varying Frequency Content
Many interesting sounds have frequency content that changes as a function of time. You can visualize this
using a spectrogram. MATLAB has a built-in command that gives you a 3-D plot with color for indicating
the amount of each frequency, as in the examples in class:
spectrogram(x,nwindow,noverlap,nt,fs,yaxis)
It has several parameters, some of which control aspects that are beyond what we will go into in this class,
but the basic principles are:
5
x: the signal that you want to create a spectrogram of
nwindow: the number of time samples in each time interval used in frequency analysis (smaller windows
give you better time resolution for seeing things like clicks, longer windows give you better frequency
resolution for seeing harmonics when the fundamental frequency is low)
noverlap: the amount of overlap of each time window used in frequency analysis (0 < noverlap <
nwindow)
nt: number of points in the t (higher numbers give more frequency resolution but take longer, should
be at least as big as nwindow, power of 2 is often used for eciency, e.g. 512 or 1024)
fs: sampling frequency of signal x
yaxis indicates that frequency goes on the y-axis, which gives pictures like what weve seen in class
A reasonable conguration for the bluenose3.wav sound (McNeill book reading snippet) is given in the
example below. Try downloading some sound les from the course source les page and computing
spectrograms. You can read them in using the wavread command, play and generate spectrograms, as in:
>> [blue, fs]=wavread(bluenose3);
>> sound(blue,fs)
>> spectrogram(blue,256,128,256,yaxis)
Get a microphone from the lab and try recording a short sound, ideally something with time-varying
characteristics. Save it with a meaningful lename and move it to your Lab 2 directory. Read the le and
its sampling frequency using the wavread command, and then compute the spectrogram.
Show the spectrogram to your TA and point out specic regions where you can connect
what you hear with what you see, e.g. where the high vs. low frequency sounds are, where
any sudden onsets are, or for speech where the vowels are.
IMPORTANT REMINDER:
Any les saved on the SCC Lab computers WILL be deleted when the computer is rebooted!!! Make sure
that you copy any les that you want to keep to your EE (or other) account. As a courtesy to others, it is
also a good idea to delete your les and working directory when you are done.
6

Das könnte Ihnen auch gefallen