How to dynamically change a sine wave sound frequency ?
Show older comments
Hello everyone.
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 to 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
I thougt about trying to create multiple audios and shifting the frequency over time so I wrote this code. However, killing the first signal in order to play a second one is not a smooth operation. Indeed, there is a blank right after the first sound is cleared...
fs = 16000;
s = generateWave(400, 1, fs, 5);
t = generateTarget(800, 1, fs, 5, 0.5);
audio = buildStereo(s, t); % Simply creates a matrix containing s and t so that it can be played in stereo
s2 = generateWave(1200, 1, fs, 5);
audio2 = buildStereo(s2, t);
soundsc(audio, fs);
pause(2)
clear sound % Not smooth, there is a blank right after the first sound is cleared
soundsc(audio2, fs)
Thank you very much.
Accepted Answer
More Answers (0)
Categories
Find more on Audio I/O and Waveform Generation in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!