Reputation: 5690
I am using the sound() function in MATLAB to generate a tone. The following function plays a tone for 4 seconds at 440Hz:
duration = 4
toneFreq = 440
samplesPerSecond = 44100; % the bit rate of the tone
y = sin(linspace(0, duration * toneFreq * 2 * pi, round(duration * samplesPerSecond))); % the equation of the sound wave
sound(y, samplesPerSecond); % play the sound wave at the specified bit rate
Occasionally (after using the function a few times), I get an error from MATLAB saying "can't register sound window". Having looked around the internet a bit, I notice this is a known bug in MATLAB (version R14 SP3) and so the general advice seems to be to use the 'audioplayer' function instead. So, I have updated my code to the following:
duration = 4
toneFreq = 440
samplesPerSecond = 44100; % the bit rate of the tone
y = sin(linspace(0, duration * toneFreq * 2 * pi, round(duration * samplesPerSecond))); % the equation of the sound wave
player = audioplayer(y, samplesPerSecond); % play the sound wave at the specified bit rate
play(player)
However, this does not produce a tone. Can anyone help in making this new code work?
Upvotes: 2
Views: 3378
Reputation: 5690
I have found the solution - the problem seems to be that the audio playback stops when the function exits. So, I have had to change play() to playblocking(). This prevents control returning until the sound finishes. It's not the ideal solution however (it would be nice to pass control back to the parent function whilst the sound still plays), but for now it will do. If anyone can suggest a way to pass control back and play the whole sound, I would appreciate it. Here is the final code:
duration = 4
toneFreq = 440
samplesPerSecond = 44100; % the bit rate of the tone
y = sin(linspace(0, duration * toneFreq * 2 * pi, round(duration * samplesPerSecond))); % the equation of the sound wave
player = audioplayer(y, samplesPerSecond); % play the sound wave at the specified bit rate
playblocking(player)
Edit: A solution has also been found that allows play to continue after the function exits. See MATLAB: Having audioplayer() continue to play after function ends.
Upvotes: 1