Reputation: 91
I am working for my class project on making a cat repellent . The application is supposed to detect cat (OpenCV implementation) and scream at the cat . However, I want my software to scream an ultrasonic sound , so that it doesn't disturb anyone around . Does anyone know how I could do that in matlab ?
Upvotes: 0
Views: 2220
Reputation: 1140
For this I would cite the answer provided by @gnovice in this thread: How do you generate dual tone frequencies in MATLAB?
His solution outlines how to generate tones of a specific frequency and duration as well as how to play and save them in Matlab.
In summary, to generate the data for a tone of 50 Hz sampled at 1kHz and lasting 2 seconds:
Fs = 1000; % Samples per second
toneFreq = 50; % Tone frequency, in Hertz
nSeconds = 2; % Duration of the sound
y = sin(linspace(0, nSeconds*toneFreq*2*pi, round(nSeconds*Fs)));
To play this sound:
sound(y, Fs); % Play sound at sampling rate Fs
Edit: removed line on amplification in light of new comments from @Bjorn
Upvotes: 1
Reputation: 11469
Ryan's answer is essentially correct, but there are more issues than I could squeeze into the comments with adequate explanation. The two main problems are:
select a standard sample rate. You need to do this to prevent your OS from sample rate converting and adding further distortion to your signal. This is usually not a big deal since the sample rate converters are very high quality, but when generating sounds close to the niquist frequency at high level, this is important.
don't multiply your signal by 10. This will create distortion and generate all kinds of problems. The standard range for audio is (-1,1), which is what you've got in y. Going outside that range may cause distortion. On some OSes (eg mac OSX) outputting outside this range won't distort if the master volume is low enough, but why play that game? Again, like issue #1, this might not be a big deal with ordinary code, but since you are close to niquist, distortion will create sounds that are no longer ultrasonic as a side-effect. If it needs to be louder, turn up your computer's system or speaker volume.
Here is my specific recommendation:
Fs = 44100; % Samples per second. 48000 is also a good choice
toneFreq = 17000; % Tone frequency, in Hertz. must be less than .5 * Fs.
nSeconds = 2; % Duration of the sound
y = sin(linspace(0, nSeconds*toneFreq*2*pi, round(nSeconds*Fs)));
sound(y,Fs); % Play sound at sampling rate Fs
If it needs to be louder, turn up your computer's system or speaker volume. If it's all the way up, you can't make it any louder in matlab. You can modify toneFreq by increasing it but keeping it less than .5 * Fs. Most computer speakers won't be outputting much at 22050, so that's why I selected 17000, which is not technically ultrasonic.
Also, test that code with toneFreq=440 (should be the same pitch as an "A" on, eg, a piano) or something, so you know it's working and you can hear about how loud it is.
Upvotes: 1