Ali P
Ali P

Reputation: 519

How can I get a sound to be presented through MATLAB for an exact duration?

I am new to sound processing and I am trying to present a tone of 0.2ms, 0.3ms and 0.4ms to a user.

The code that I did is as follows: (MATLAB)

Fs = 16000;
duration = 0.2;
level = 0;
freq1 = 500;
t = 0: 1/Fs : duration*(Fs-1)/Fs;
fa1 = 10^(level/20);
y1 = fa1*sin(2*pi*freq1*t)';
ap = audioplayer(y1,Fs);
tic
playblocking(ap)
toc

The time I obtained from the tic,toc functions is 0.56 for a 0.2s duration I specified.

Is there anyway to make it present for exactly 0.2s?

Upvotes: 1

Views: 280

Answers (3)

Nick Haddad
Nick Haddad

Reputation: 8927

Gordon's assumption is correct here. It takes time to start the audio stream and stop the audio stream. You can verify this by putting separate tic/toc calls inside the audioplayer/playblocking, resume, and stop methods.

You can then subtract the times of the pause and resume tic/toc from the playblocking call.

Audio player should only des the samples you give it to the soundcard.

Alternatively you can plug the audio output into the audio input on your soundcard and use audio recorder to record the audio back into MATLAB, then measure the number of samples in the signal.

Upvotes: 1

marsei
marsei

Reputation: 7751

You may write a sound file with the wavwrite function that takes y1 and Fs variables as input. Then open the .wav with a sound editor (audacity for example) and check the exact timing.

Upvotes: 2

Gordon Bean
Gordon Bean

Reputation: 4602

My guess is that the sound persists for exactly the specified time. The discrepancy you are getting from tic and toc is the overhead required for calling the function, etc.

You could test this hypothesis by trying different lengths of sound. I suspect the overhead time should remain more or less constant relative to the time you play the sound. If you consistently get a tic-toc time of 0.3 sec longer than the time you expect the sound to play, then you can probably chalk the discrepancy off to overhead.

Upvotes: 3

Related Questions