The duration this vector will play depends on the number of elements in the vector and the sampling frequency. For example, a 1000-element vector, when it is reproduced at a frequency of 1 kHz, will last 1 second. When playing at a frequency of 500 Hz, it lasts 2 seconds. Therefore, the first choice you must make is the sample 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 can do this even more to avoid attenuation of frequencies close to the sample rate.
Given a sampling frequency of 1 kHz, the following example creates an audio vector of a given duration and tone frequency (using LINSPACE and SIN ):
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 playing back 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
Then the vector can 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
Now the sound vector can be loaded using the WAVREAD function. If you intend to combine two sound vectors, you must make sure that they are both designed to use the same sampling rate.
gnovice
source share