play sound only while key is pressed

I'm writing a very very simple keyboard and when a button is pressed my program generates the sound. But when the button is not pressed anymore the sound doesnt dissapear. How can I chceck if the button is pressed? I want the sound only when i hold the button pressed...
taht's the method i use to generate the sound:
function [] = playFreq(app,freq)
amp=10;
fs=20500;
duration=10;
values=0:1/fs:duration;
a=amp*sin(2*pi* freq*values);
sound(a);
end

Réponses (1)

Walter Roberson
Walter Roberson le 21 Jan 2019

0 votes

You cannot use sound() for this purpose. sound() always plays the entire buffer.
If you use audioplayer with the play() method then you can play a single buffer but you can stop() it early.
If you need to repeat indefinitely while the button is pressed then you will need to use the Audio Systems Toolbox (or the DSP Toolbox if you have R2017a or earlier.)

Catégories

En savoir plus sur Audio I/O and Waveform Generation dans Centre d'aide et File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by