tags:

views:

1530

answers:

2

I'm interested in producing a tone frequency at runtime with the frequency and duration being variable parameters. What would be the best way of generating this sound file in MATLAB and have it accessible in the script for use later to be concatenated with other sound files generated in a similar fashion for different frequencies/durations? Thanks in advance for the comments.

+2  A: 

This page on the MATLAB website is a pretty good reference for sound generation using MATLAB.

Robert Harvey
+3  A: 

The duration for which a given vector will play depends on the number of elements in the vector and the sampling rate. For example, a 1000-element vector, when played at 1 kHz, will last 1 second. When played at 500 Hz, it will last 2 seconds. Therefore, the first choice you should make is the sampling rate you want to use. To avoid aliasing, the sampling rate should be twice as large as the largest frequency component of the signal. However, you may want to make it even larger than that to avoid attenuation of frequencies close to the sampling rate.

Given a sampling rate of 1 kHz, the following example creates a sound vector of a given duration and tone frequency (using the LINSPACE and SIN functions):

Fs = 1000;      % Samples per second
toneFreq = 50;  % Tone frequency, in Hertz
nSeconds = 2;   % Duration of the sound
y = sin(linspace(0,nSeconds*toneFreq*2*pi,round(nSeconds*Fs)));

When played at 1 kHz using the SOUND function, this vector will generate a 50 Hz tone for 2 seconds:

sound(y,Fs);  % Play sound at sampling rate Fs

The vector can then be saved as a wav file using the WAVWRITE function:

wavwrite(y,Fs,8,'tone_50Hz.wav');  % Save as an 8-bit, 1 kHz signal

The sound vector can later be loaded using the WAVREAD function. If you're going to concatenate two sound vectors, you should make sure that they are both designed to use the same sampling rate.

gnovice
Do I specify the frequency in the Fs variable? I would like to have a systematic method of figuring out how to generate a particular tone at the same time period though. What would be your recommendations on that?
stanigator
@stanigator: I revised the code to make it more general. It computes the sound vector given the sampling frequency, tone frequency, and duration.
gnovice

related questions