Skip to content Skip to sidebar Skip to footer

Android: How To Generate A Frequency?

Is there a nice way in Android to generate and then play a frequency (eg. 1000hz, 245hz)?

Solution 1:

Take a look at android.media.ToneGenerator.

You can also try following Code.

publicclassPlaySoundextendsActivity {
    // originally from http://marblemice.blogspot.com/2010/04/generate-and-play-tone-in-android.html// and modified by Steve Pomeroy <steve@staticfree.info>privatefinalintduration=3; // secondsprivatefinalintsampleRate=8000;
    privatefinalintnumSamples= duration * sampleRate;
    privatefinaldouble sample[] = newdouble[numSamples];
    privatefinaldoublefreqOfTone=440; // hzprivatefinalbyte generatedSnd[] = newbyte[2 * numSamples];

    Handlerhandler=newHandler();

    @OverridepublicvoidonCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

    @OverrideprotectedvoidonResume() {
        super.onResume();

        // Use a new tread as this can take a whilefinalThreadthread=newThread(newRunnable() {
            publicvoidrun() {
                genTone();
                handler.post(newRunnable() {

                    publicvoidrun() {
                        playSound();
                    }
                });
            }
        });
        thread.start();
    }

    voidgenTone(){
        // fill out the arrayfor (inti=0; i < numSamples; ++i) {
            sample[i] = Math.sin(2 * Math.PI * i / (sampleRate/freqOfTone));
        }

        // convert to 16 bit pcm sound array// assumes the sample buffer is normalised.intidx=0;
        for (finaldouble dVal : sample) {
            // scale to maximum amplitudefinalshortval= (short) ((dVal * 32767));
            // in 16 bit wav PCM, first byte is the low order byte
            generatedSnd[idx++] = (byte) (val & 0x00ff);
            generatedSnd[idx++] = (byte) ((val & 0xff00) >>> 8);

        }
    }

    voidplaySound(){
        finalAudioTrackaudioTrack=newAudioTrack(AudioManager.STREAM_MUSIC,
                sampleRate, AudioFormat.CHANNEL_CONFIGURATION_MONO,
                AudioFormat.ENCODING_PCM_16BIT, numSamples,
                AudioTrack.MODE_STATIC);
        audioTrack.write(generatedSnd, 0, generatedSnd.length);
        audioTrack.play();
    }
}

Post a Comment for "Android: How To Generate A Frequency?"