Reputation: 149
I am new to android.
Can someone help me with a non-deprecated code to generate a tone of F frequency and S second duration
I found this but it uses deprecated methods.
Upvotes: 1
Views: 78
Reputation: 5042
Here is a rendition of the linked code, adapted for API level 23+, with a parameter added for tone duration:
short generatedSnd[];
int sampleRate = 44100;
float freqOfTone = 1000; //Hz
float amplitude = 10000; //0..32767 (0x7FFF)
float lengthSeconds = 1.0f;
private void genTone(){
int numSamples = (int) (sampleRate * lengthSeconds);
generatedSnd = new short[numSamples];
// fill out the array
for (int i = 0; i < numSamples; ++i) {
generatedSnd[i] = (short) (Math.sin(2 * Math.PI * i / (sampleRate/freqOfTone)) * amplitude);
}
}
private void playSound(){
AudioTrack audioTrack = new AudioTrack.Builder()
.setAudioFormat(
new AudioFormat.Builder()
.setEncoding(AudioFormat.ENCODING_PCM_16BIT)
.setSampleRate(sampleRate)
.setChannelMask(AudioFormat.CHANNEL_OUT_MONO)
.build()
)
.setTransferMode(AudioTrack.MODE_STATIC)
.setBufferSizeInBytes(generatedSnd.length * 2) //2 bytes-per-sample
.build();
audioTrack.write(generatedSnd, 0, generatedSnd.length);
audioTrack.play();
}
This code has been tested up to 50s in the emulator, but it may crash at higher play times, due to the size being passed to setBufferSize()
. Note it does not include other advanced features to help you handle arbitrarily long play times, such as 1.) streaming playback, or 2.) phase correction due to float
quantization errors at values far from 0.
It should work fine for durations less than about 10 seconds, however.
Also omitted is the AudioTrack cleanup code (stop()
/release()
).
Upvotes: 1