How to modify an audio signal on the fly?

Viewed 74

I'm currently programming an application which goal is to generate audio sine waves such that frequencies increase or decrease over time. However the user should be able to use up and down keys in order to counter this drift. For example : if the frequency is decreasing over time, the user should be able to press the up key to increase it dynamically.

The thing is I can't find any information on how to do such a thing. I've been using the soundsc(audio, fs) function which allows to play a sound at a given sample rate, but I always must create the sine wave before feeding it to the function which leaves no room for dynamic variations.

Is it possible to do this in Matlab ? If so, what function allows you to make this ? If there is no function for that, how should I proceed ?

Here is my current code if you want to take a look at it :

% soundTesting.m

fs = 16000;
s = generateWave(400, 1, fs, 5);
t = generateTarget(800, 1, fs, 5, 0.5);
audio = [s; t]';
% Playing audio in stereo with target audio on the right speaker and drifting sine wave on the left
% Note that for now the sine wave is not drifting at all.
soundsc(audio, fs);

%generateWave.m

function wave = generateWave(frequency, amplitude, fs, length)
    ts = 1 / fs;
    t = 0 : ts : length;
    wave = amplitude * sin(2 * pi * frequency * t);
end

%generateTarget.m

function target = generateTarget(frequency, amplitude, fs, length, span)
    wave = generateWave(frequency, amplitude, fs, length);
    target = zeros(size(wave));
    for i = 1 : length - 1
        % Every second, emit the target sound for span seconds.
        target(i * fs : i * fs + int32(span * fs)) = wave(i * fs : i * fs + int32(span * fs));
    end
end

Thank you very much.

1 Answers

You need to use some kind of buffered audio output, so that you can pass a block of samples into the buffer and they will be fed to the output by a separate task with the right timing.

If your licence includes the Audio Toolbox, have a look at the Mathworks page here. If not you could try this from the MATLAB file exchange.

Related