Generate tone of a specific frequency

suggest change

To play a sound with a specific tone, we first have to create a sine wave. This is done in the following way.

final int duration = 10; // duration of sound
final int sampleRate = 22050; // Hz (Nyquist limit is sampleRate / 2, 11025 Hz)
final double frequency = 440; // Hz
final int numSamples = duration * sampleRate;
final double samples[] = new double[numSamples];
final short buffer[] = new short[numSamples];
for (int i = 0; i < numSamples; ++i) 
{
 samples[i] = Math.sin(2 * Math.PI * i * frequency / sampleRate); // Sine wave
 buffer[i] = (short) (samples[i] * Short.MAX_VALUE);  // Higher amplitude increases volume
}

Now we have to configure AudioTrack to play the generated buffer. It is done in the following manner.

AudioTrack audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,
                    sampleRate, AudioFormat.CHANNEL_OUT_MONO,
                    AudioFormat.ENCODING_PCM_16BIT, buffer.length * 2,
                    AudioTrack.MODE_STATIC);

Write the generated buffer and play the track

audioTrack.write(buffer, 0, buffer.length);
audioTrack.play();

Hope this helps :)

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents