Creating a continuous tone in MATLAB whose frequency varies in real-time depending on user input

1.5k views Asked by At

I am currently working on a graphing program in MATLAB that takes input and maps a point to x-y space using this input. However, the program should also output a continuous tone whose frequency varies depending on the location of the point.

I was able to get the tone generation done, however could not get the tone to work continuously due to the nature of the program. (Code in between tone generations) I thought I could solve this using a parfor loop with the code that alters the frequency in one iteration of the loop, and the code that generates the tone in another but cannot seem to get it due to the following error:

Warning: The temporary variable frequency will be cleared at the beginning of each iteration of the parfor loop. Any value assigned to it before the loop will be lost. If frequency is used before it is assigned in the parfor loop, a runtime error will occur. See Parallel for Loops in MATLAB, "Temporary Variables".

In multiThreadingtest at 5 Error using multiThreadingtest (line 5) Reference to a cleared variable frequency.

Caused by: Reference to a cleared variable frequency.

And my code:

global frequency

frequency = 100;

parfor ii=1:2
    if ii==1
        Fs = 1000;
        nSeconds = 5;
        y = 100*sin(linspace(0, nSeconds*frequency*2*pi, round(nSeconds*Fs)));
        sound(y, Fs);
    elseif ii==2
        frequency = 100
        pause(2);
        frequency = 200
        pause(2);
        frequency = 300
        pause(2);
    end
end
1

There are 1 answers

0
marsei On

The solution may not come from multithreading, but from the use of another function to output a tone(audioplayer, play, stop). 'audioplayer/play' has the ability to output sounds that overlap in time. So basically, a pseudo code would be:

get the value of the input  
generate/play a corresponding 5 second tone  
detect if any change in the input  
 if no change & elapsed time close to 5 seconds  
  generate/play an identical 5 second tone  
 if change   
  generate a new 5 second tone  
  %no overlapping
    stop old  
    play new  
  %overlapping (few milliseconds)
    play new
    stop old  

The matlab code showing the 'sound'/'play' differences.

Fs = 1000;  
nSeconds = 5;  

frequency = 100;  
y1 = 100*sin(linspace(0, nSeconds*frequency*2*pi, round(nSeconds*Fs)));  
aud1 = audioplayer(y1, Fs);  

frequency = 200;  
y2 = 100*sin(linspace(0, nSeconds*frequency*2*pi, round(nSeconds*Fs)));  
aud2 = audioplayer(y2, Fs);  


% overlapping sound impossible  
sound(y1, Fs);  
pause(1)  
sound(y2, Fs);  

% overlapping sound possible  
play(aud1);  
pause(1);  
disp('can compute here');
play(aud2);  

pause(1);  
stop(aud1);  
pause(1);  
stop(aud2);