Lab2

Published on April 2017 | Categories: Documents | Downloads: 14 | Comments: 0 | Views: 227
of 6
Download PDF   Embed   Report

Comments

Content


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-files 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 different people to run the M-files that you create in this lab. You can work together to
implement them, and different people can work on different 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 figure 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 first
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-files, 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 MATLAB—just the syntax may be different.
The general form for for loops is:
for variable = startingvalue : stepsize : endingvalue
. . . some MATLAB statements . . .
end
At the beginning of the first 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 first line assigns the value 0 to the variable z. Then the for loop begins: the variable n is set to the
first value 1. The single line within the for loop sets z to z+n, so on the first 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 final 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 definition 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 effect could
be accomplished using the B=fliplr(A) operation in MATLAB.
1.2 M-files
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 file containing
a sequence of commands, called an M-file (its filename will end in “.m”), and run all the commands in the
M-file at the end. M-files 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-files can be saved, so they can be run multiple
times and easily changed if you want to do some step differently. Another reason is that for larger projects,
it’s good to divide up your task into smaller pieces and M-files make this easier.
There are actually two types of M-files: 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-file 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. We’ll 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 Beethoven’s Fifth is due to Virginia Stonick.
2
about creating folders, saving and uploading M-files, 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-files 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 different directory
or new name to make sure you don’t accidentally use someone else’s M-files.
Move the “beethoven.m” file 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 file (e.g. “beethoven” not “beethoven.m”) in the
Command window. Try it. If you are in the folder with the correct M-file, you should here a short sequence
of notes from Beethoven’s 5th.
To start a new M-file, you can again click on the “file” pulldown menu button but then go to “new” and
then to “M-file,” or there’s a shortcut “open blank M-file” icon you can click on, shown in Figure 1. This
will open up the MATLAB editor. To edit an existing M-file, you can click on its name in the list of files for
the current directory panel, click on the “file” pulldown menu button in the upper right of the MATLAB
window and then go to “open”, or click on the open file icon in the upper right of the MATLAB window
(next to the “open blank M-file” 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-file 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-file and add the commands you want in the order you want them to be executed,or
you can start from an existing M-file.
2: Save and run the M-file.
3: Make any changes to the commands in the M-file 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-file has a problem. Check that when the error message says that a file is not found.)
4: Repeat steps 2 and 3 until you have an M-file that does what you want.
3
Note that M-files can contain commands that correspond to other M-files.
Open the “beethoven.m” script in the MATLAB editor. In this file, 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 affect the way your file runs. Try
changing something in the beethoven.m file so that it sounds a little different (e.g. different length notes or
pauses). Reading the comments should be helpful.
When you are editing an M-file, you can run it by either clicking on the “run” icon at the top of the
open M-file, or by typing the name of the file (without the ‘.m’ part) into the Command Window. (You can
also run an M-file by typing the name of the file in another M-file, and then running the other M-file.) Note
that the M-file 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-file 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 file, but save it with a different name, e.g. “mysong.m”. Don’t 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-file.
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 file 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 file “mysong.wav” in your working directory.
Run your new M-file for your TA by clicking on the “run” icon at the top of the M-file
editor. Submit the M-file and associated audio file 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, we’re using one
particular transform, the Fourier transform. The Fourier transform uses sinusoids of different 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(2πf
k
t + φ
k
) =

k
A
k
cos(2πkf
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, we’ll 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 soundfile “horn11short.wav” and the M-files
getfreqs.m, cosgen.m and cosgen.fig 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 different 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 different. 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,nfft,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)
• nfft: number of points in the fft (higher numbers give more frequency resolution but take longer, should
be at least as big as nwindow, power of 2 is often used for efficiency, 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 we’ve seen in class
A reasonable configuration for the “bluenose3.wav” sound (McNeill book reading snippet) is given in the
example below. Try downloading some sound files from the course “source files” 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 filename and move it to your Lab 2 directory. Read the file and
its sampling frequency using the wavread command, and then compute the spectrogram.
Show the spectrogram to your TA and point out specific 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 files saved on the SCC Lab computers WILL be deleted when the computer is rebooted!!! Make sure
that you copy any files 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 files and working directory when you are done.
6

Sponsor Documents

Or use your account on DocShare.tips

Hide

Forgot your password?

Or register your new account on DocShare.tips

Hide

Lost your password? Please enter your email address. You will receive a link to create a new password.

Back to log-in

Close