Last active
December 12, 2022 22:31
-
-
Save slightfoot/6330866 to your computer and use it in GitHub Desktop.
Android Tone Generator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Usage: | |
// AudioTrack tone = generateTone(440, 250); | |
// tone.play(); | |
// | |
private AudioTrack generateTone(double freqHz, int durationMs) | |
{ | |
int count = (int)(44100.0 * 2.0 * (durationMs / 1000.0)) & ~1; | |
short[] samples = new short[count]; | |
for(int i = 0; i < count; i += 2){ | |
short sample = (short)(Math.sin(2 * Math.PI * i / (44100.0 / freqHz)) * 0x7FFF); | |
samples[i + 0] = sample; | |
samples[i + 1] = sample; | |
} | |
AudioTrack track = new AudioTrack(AudioManager.STREAM_MUSIC, 44100, | |
AudioFormat.CHANNEL_OUT_STEREO, AudioFormat.ENCODING_PCM_16BIT, | |
count * (Short.SIZE / 8), AudioTrack.MODE_STATIC); | |
track.write(samples, 0, count); | |
return track; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
set durationMs really high, then add the following after the above code:
track.setLoopPoints(0, track.getBufferSizeInFrames(), -1);
or
track.setLoopPoints(0, samples.length / 2, -1);
for older versions of android i think
-1 makes it loop indefinetly, or can set it to a high number if you want