Search code examples
matlabaudioclickfrequency

Combining frequencies


I am designing a sound signal in MATLAB that is composed of certain (10-12) frequencies. Each frequency tone is of 1 ms duration. When I am changing between frequencies, the change is abrupt and creating unwanted click sounds. The orange triangle in the image shows the change of frequencies:

change of frequencies

How do I transition from one frequency to another? Currently I am just appending tones together.

Time = (0: ToneDur * Fs)/Fs;
Sound = zeros(1,100000);  % Zero padding
for i = 1 : TotalFreq
    Tone = Amp(i).*cos(2 * pi * Frequency(i) * Time);
    Sound = [Sound, Tone];
end

Solution

  • The simplest method will be just to generate only whole periods of a given frequency. You will first need to create an array of the frequencies to be generated then calculate the linear period in samples. With a given duration you can the calculate how many periods of the wave can fit in the given time duration. For frequencies with partial periods, simply round the number of periods. This will mean that not all frequency truly play to the same period of time but the difference should not be enough to actually notice, especially for higher frequencies.

    Using the coding convention of your question, this will do the trick

    Fs = 44100; % sampling rate
    ToneDur = 0.15; % duration of tone in seconds
    Frequency = [1:0.5:12] * 100;  % array of frequencies (100hz - 12khz in 50Hz steps)
    TotalFreq = length(Frequency); % the number of frequencies
    
    freqLengths = (1 ./ Frequency) * Fs; % wave period in samples
    numberOfPeriodsPerFreq = Fs * ToneDur ./ freqLengths
    sampDur = floor(numberOfPeriodsPerFreq) .* freqLengths % array number of samples required per frequency for a whole number of periods
    
    Sound = 0; % instantiate variable to store audio data
    
    for i = 1 : TotalFreq
      Tone = sin(2 * pi * Frequency(i) * [0:sampDur(i)]/Fs);
      Sound = [Sound , Tone];
    end
    
    soundsc(Sound, Fs) % play audio